I want to change all the values that fulfill a certain criterium in a C# dictionary.
Simply editing the values like this
foreach (var kv in dictionary)
{
kv.Value += 1;
}
does not work because the KeyValuePair
of the foreach
loop is read only.
However, editing the entries directly like this:
foreach (var kv in dictionary)
{
dictionary[kv.Key] = kv.Value + 1;
}
also doesn't work, because it modifies the collection and breaks the iterator.
At this point, the only remaining solution I can think of is storing all keys of the dictionary in a list, and then using that to edit the values during a second loop, however, that seems like a pretty inelegant solution to me.
Is there any better alternative?