Generics - Extension methods DictionaryltTKeyTValuegt.RemoveAll Is it possible

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

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

public static void RemoveAll<TKey,TValue>(this Dictionary<TKey,TValue> dict, 
                                     Func<KeyValuePair<TKey,TValue>,bool> condition)
{
    foreach ( var cur in dict.Where(condition).ToList() ) {
      dict.Remove(cur.Key);
    }
}
  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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/654441/extension-methods-dictionarytkey-tvalue-removeall-is-it-possible

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils