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

11,554

Solution 1

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;

Solution 2

In .net 5 the following snippet no longer throws:

var d = new Dictionary<string, int> { { "a", 0 }, { "b", 0 }, { "c", 0 }};

foreach (var k in d.Keys){
      d[k] = 1;
}
Share:
11,554
Chev
Author by

Chev

I'm a passionate developer and I love to learn. I also love to share my knowledge with others. Both of those are the primary reasons why I'm here on Stack Overflow :)

Updated on July 29, 2022

Comments

  • Chev
    Chev almost 2 years

    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?

  • Chev
    Chev almost 13 years
    Gah, it's always something so simple. Duh; it must be late. Thank you! Will accept in 12 minutes when I am able :)
  • Rick Sladkey
    Rick Sladkey almost 13 years
    Unfortunately, this is not safe to do if keys are being added by a background thread.
  • Amy B
    Amy B over 7 years
    @kami ToList is an extension method defined on System.Linq.Enumerable, which is .net 3.5. You'll need to find another way to create an extra collection to use as an enumeration source.