I’ve been trying to write an extension method to mimic List.RemoveAll(Predicate).
So far I’ve got this:
public static void RemoveAll<TKey,TValue>(this Dictionary<TKey,TValue> dict, Predicate<KeyValuePair<TKey,TValue>> condition) { Dictionary<TKey,TValue> temp = new Dictionary<TKey,TValue>(); foreach (var item in dict) { if (!condition.Invoke(item)) temp.Add(item.Key, item.Value); } dict = temp; }
Any pointers? Is this a completely naive implementation?
Your code will not work because you are passing the Dictionary class by value. This means the final assignment (dict = temp) will not be visible to a calling function. It is not legal in C# to pass extension method targets by ref or out (in VB it’s legal to do ByRef).
Instead you will need to modify the Dictionary inline. Try the following
EDIT
Swapped the order of Where and ToList to reduce the size of the allocated memory of the list. It will now only allocate a list for the items that are to be removed.