[ACCEPTED]-How to remove all elements from a dictionary?-.net

Accepted answer
Score: 37

A much simpler (and much more efficient) approach:


and 2 yes, the error is because changing the data 1 deliberately breaks iterators.

Score: 6

Try using the Clear method instead.

internal static void RemoveAllSourceFiles()

Update: And as Marc 5 pointed out, you cannot continue iterating 4 over a collection while you modify it because 3 the iterator is irrecoverably invalidated. Please 2 read the answer to this SO question for 1 details.

Why does enumerating through a collection throw an exception but looping through its items does not

Score: 4
Score: 2

To do what you want to do you are going 4 to need to iterate through the keys in reverse, that 3 way you do not modify the array in the order 2 it is trying to return to you.

Either that 1 or use .Clear()

Score: 2

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

If you want better control 6 over deletion, use linq:

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

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

Score: 0

I know this is an old question, but for 2 any who's looking for an answer, here some 1 options:

  • To list() and then use the .remove property.
  • Make it null/nothing and reinit it?
  • Forloop in stead of foreach?
while Dict.Count()
  clDictObject oBj = Dict.Keys.ElementAt(dict.Count -1);
end while

More Related questions