I want to remove items with the maximum value in a Dictionary<TKey, TValue>
. I use Where
to query the maximum value's key, and useforeach
to remove it. But it throw a System.InvalidOperationException
in foreach
statement, the message is Collection was modified; enumeration operation may not execute.
But I don't think I have modified the collection at all in foreach
!
Here is an example:
Dictionary<char, int> dic = new Dictionary<char, int>();
dic['a'] = 5;
dic['b'] = 10;
var maxVal = dic.Values.Max();
var maxs = dic.Where(kv => kv.Value == maxVal);
foreach(var entry in maxs)//the exception is thrown here
{
dic.Remove(entry.Key);//I don't modify maxs at all! I just remove items in dic!
}