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

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

    The fastest way to remove would be either:

    public static void RemoveAll(this IDictionary idict, Func, bool> predicate)
        {
            foreach (var kvp in idict.Where(predicate).ToList())
            {
                idict.Remove(kvp.Key);
            }
        }
    

    or

    public static void RemoveAll(this ICollection icollection, Predicate predicate)
    {
        var nonMatchingItems = new List();
    
        // Move all the items that do not match to another collection.
        foreach (var item in icollection) 
        {
            if (!predicate(item))
            {
                nonMatchingItems.Add(item);
            }
        }
    
        // Clear the collection and then copy back the non-matched items.
        icollection.Clear();
        foreach (var item in nonMatchingItems)
        {
            icollection.Add(item);
        }
    }
    

    depending on whether you have more cases of predicate returning true or not. Both are O(N) in nature, but 1st approach will be faster if you have very less cases of "removal/lookup", and the second one faster if items in collection matches the condition majority of the times.

提交回复
热议问题