Alex Rivera | Logout

How to remove all elements from a dictionary?

Asked 2011-03-09T07:24:52.147
12

I use the following code to remove all elements from a dictionary:

internal static void RemoveAllSourceFiles()
        {
            foreach (byte key in taggings.Keys)
            {
                taggings.Remove(key);
            }
        }

But unfortunately this isn't working because an InvalidOperationException is thrown. I know this is because the collection is modified while iterating over it, but how can I change that?

Edit
Report

1 Answer

2

As said, the .NET default enumerator doesn't support collection changes while enumerating. In your case use Clear.

If you want better control over deletion, use linq:

var deletionList = (from tag in taggings where <where clause> select tag.Key).ToArray();
foreach(var key in deletionList)
{
   taggings.Remove(key);
}

The ToArray() extension method will enumerate the LINQ query, and instantiate an array storing the results. This array can be safely enumerated later to delete the contained items in the source dictionary.

answered 2011-03-09T07:31:26.083

Your Answer