Search code examples
c#linqloopsdictionaryenumeration

How to change all values in a Dictionary<string, bool>?


So I have a Dictionary<string, bool> and all I want to do is iterate over it and set all values to false in the dictionary. What is the easiest way to do that?

I tried this:

foreach (string key in parameterDictionary.Keys)
    parameterDictionary[key] = false;

However I get the error: "Collection was modified; enumeration operation may not execute."

Is there a better way to do this?


Solution

  • Just change the enumeration source to something other than the dictionary.

    foreach (string key in parameterDictionary.Keys.ToList())
      parameterDictionary[key] = false;
    

    For .net 2.0

    foreach (string key in new List<TKey>(parameterDictionary.Keys))
      parameterDictionary[key] = false;