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

前端 未结 7 500
后悔当初
后悔当初 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:44

    Instead of removing, just do the inverse. Create a new dictionary from the old one containing only the elements you are interested in.

    public Dictionary NewDictionaryFiltered
    (
      Dictionary source,
      Func filter
    )
    {
    return source
      .Where(x => filter(x.Key, x.Value))
      .ToDictionary(x => x.Key, x => x.Value);
    }
    

提交回复
热议问题