Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Chev Avatar asked May 27 '11 04:05

Chev


People also ask

Can dictionary key be a string in python?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Are python dictionary keys mutable?

As shown in the figure below, keys are immutable ( which cannot be changed ) data types that can be either strings or numbers. However, a key can not be a mutable data type, for example, a list. Keys are unique within a Dictionary and can not be duplicated inside a Dictionary.

Can a dictionary hold different data types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.

How c# dictionary works?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.


1 Answers

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;
like image 126
Amy B Avatar answered Sep 19 '22 10:09

Amy B