Is there any way to edit the Values of a Dictionary during iteration?

Viewed 62

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?

2 Answers

You could create an array (or a List with .ToList()) from the .Keys in the foreach, something like this:

foreach (string key in dictionary.Keys.ToArray())
{
    dictionary[key] += 1;
}

You can use ToDictionary to create new Dictionary and change the origin in the loop, like :

foreach (var kv in dictionary.ToDictionary(k=>k.Key,v=>v.Value))
{
   dictionary[kv.Key] = kv.Value + 1;
}

I hope you find this helpful.

Related