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

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

    Modified version of Aku's extension method solution. Main difference is that it allows the predicate to use the dictionary key. A minor difference is that it extends IDictionary rather than Dictionary.

    public static class DictionaryExtensions
    {
        public static void RemoveAll(this IDictionary dic,
            Func predicate)
        {
            var keys = dic.Keys.Where(k => predicate(k, dic[k])).ToList();
            foreach (var key in keys)
            {
                dic.Remove(key);
            }
        }
    }
    
    . . .
    
    dictionary.RemoveAll((k,v) => v.Member == foo);
    

提交回复
热议问题