Generic Dictionary and Resetting All Values

Created: December 26, 2014 Tagged As: .net, C#, Language Share:

I often store values in a generic dictionary when performing reporting or other set-based operations. They provide a type-safe mechanism for storing working data. I recently ran into an issue where I was using such a dictionary and needed to reset the values for each group of subtotals I was calculating.

Here is the dictionary I defined:

Dictionary<intdouble> myDictionary = new Dictionary<intdouble>(); 
myDictionary.Add(0, 34.12F); 
myDictionary.Add(1, 12.34F); 
myDictionary.Add(2, 14.4F); 

I then tried, logically I thought, to reset the values like this:

foreach (int key in myDictionary.Keys) 
   myDictionary[key] = 0F; 

However, this threw the following exception: "Collection was modified; enumeration operation may not execute."

​Hmmm. How to solve this? Apparently, the Key collection needs to be cast to a list or array or something that will be temporarily held in RAM during the loop. I opted for the List option as follows:

foreach (int key in myDictionary.Keys.ToList())
   myDictionary[key] = 0F; 
That worked like a charm!