how to change Dictionary’s value when enumerate it?
the following code doesn’t work, because we can not change dictionary’s value when enumerating it. Is there any way to get around it? Or NO WAY? Thanks
foreach (KeyValuePair<string, int> kvp in mydictionary)
{
if (otherdictionary.ContainsKey(kvp.Key))
{
mydictionary[kvp.Key] = otherdictionary[kvp.Key];
}
else
{
otherdictionary[kvp.Key] = mydictionary[kvp.Key];
}
}
Make a copy of the values you need to enumerate over before you enumerate over them, then you can change the original source.
Since you don’t actually use the value, you can change the code to this:
Note the use of
.ToArray()there to make a temporary array copy of the key collection. This is now separate from the source dictionary, so you can change the dictionary all you want.