Best way to remove multiple items matching a predicate from a c# Dictionary?

前端 未结 7 474
后悔当初
后悔当初 2020-12-09 01:17

I need to remove multiple items from a Dictionary. A simple way to do that is as follows :

  List keystoremove= new List();
  for         


        
7条回答
  •  借酒劲吻你
    2020-12-09 01:43

    Here's an alternate way

    foreach ( var s in MyCollection.Where(kv => kv.Value.Member == foo).ToList() ) {
      MyCollection.Remove(s.Key);
    }
    

    Pushing the code into a list directly allows you to avoid the "removing while enumerating" problem. The .ToList() will force the enumeration before the foreach really starts.

提交回复
热议问题