I have the following code in C# where vector is a [string,double] type of Dictionary.I want to divide all values in this dictionary by a value, "magnitude". Now, my naive first code was the following:
foreach (var key in vector.Keys)
{
vector[key] = vector[key] / magnitude;
}
Which throws an exception, saying the Collection has been modified in a foreach. I may create a second dictionary to write the resulting values into, but I do not want this way.
Is there any easier way to do that, for example by using methods which operate on all Dictionary values, like the following?
vector.Values().Aggreagate(), vector.Values().Average()
The simplest way to do this is just to copy the list of keys before iterating:
foreach (var key in vector.Keys.ToList())
{
vector[key] = vector[key] / magnitude;
}
Or:
foreach (var entry in vector.ToList())
{
vector[entry.Key] = entry.Value / magnitude;
}
(That avoids a double lookup, but will copy more data of course.)
It's a bit of a shame that modifying the value of an existing entry is seen as a change that prevents you from continuing to iterate over the keys, admittedly.
An alternative would be to have a mutable wrapper type as the value, then you could use:
foreach (var wrapper in vector.Values)
{
wrapper.Value = wrapper.Value / 10;
}
That wouldn't be modifying the dictionary at all - just the objects that the dictionary refers to. I personally wouldn't do this in most cases, but it may be appropriate for you.
See more on this question at Stackoverflow