0

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!
        }
huangbiubiu
  • 1,252
  • 20
  • 37
  • 2
    It looks like you're confused by how `Where()` works. Materialize the collection first by calling `Where(...).ToList()`. See [duplicate](http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute). – CodeCaster Mar 16 '16 at 12:04
  • 1
    He didn't realise he was editing `dic` when he was editing `maxs`. The linked-to solution fixes this because the use of `dic.Where(...).ToList()` would make `maxs` a new list and thus he can iterate `maxs` while removing items from `dic`. – Neil Barnwell Mar 16 '16 at 12:12

0 Answers0