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

前端 未结 7 479
后悔当初
后悔当初 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 02:01

    you can create an extension method:

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

提交回复
热议问题