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?
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With