Click here to Skip to main content
15,881,709 members
Articles / Programming Languages / C#
Tip/Trick

Implementing Dictionary.RemoveAll

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
14 May 2013CPOL1 min read 27.5K   10   3
Implementing Dictionary.RemoveAll as an extension method

Introduction

Before I start, this is my first post - hope it is useful to at least a few readers. I've tried to start off with a simple topic - please comment on the general style and usability. I'll definitely do some more complicated posts and articles later on.  

.NET implements RemoveAll for any IList<T> but does not do so for IDictionary<K, V>. IList.RemoveAll removes any element that matches the predicate provided, IDictionary.RemoveAll does the same. 

Using the code

Copy and paste the extension method into any static class in your project (I always have at least one for extension methods). 

The code for the extension method:  

C#
public static void RemoveAll<K, V>(this IDictionary<K, V> dict, Func<K, V, bool> match)
{
    foreach (var key in dict.Keys.ToArray()
            .Where(key => match(key, dict[key])))
        dict.Remove(key);
} 

An example of using it: 

C#
var dictionary = new Dictionary<string, int>();
dictionary["A"] = 0;
dictionary["B"] = 1;
dictionary["C"] = 2;
dictionary["D"] = 3;
//The next line will remove the items with keys "C" and "D"
//since they both have values that are larger than 1
dictionary.RemoveAll((key, value) => value > 1); 

Points of Interest

A note on the implementation of the extension method:

Since you cannot remove items from an enumeration (the right side of a foreach statement is always an enumeration) during foreach, LINQ's .ToArray() is used to build an array of the items that should be removed and then the removals are done afterwards. This provides an easy-to-use syntax that is readable and does all the caching in one line. Of course, if you wanted to use this in performance critical situations or for high volumes of rows there are much better ways. 

History

  • 2012/11/16 - Posted.
  • 2012/11/17 - Updated with performance enhancement recommended by George Swan. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Coderon Technologies
South Africa South Africa
Michiel du Toit is a software developer based in Bloemfontein, South Africa focusing on development using C# and SQL Server (both WinForms and ASP.NET).

Comments and Discussions

 
QuestionFaster Alternative? Pin
George Swan16-Nov-12 7:47
mveGeorge Swan16-Nov-12 7:47 

Michiel -Thanks for the tip. The method seems to run twice as fast if the Keys collection is
converted to an array.


C#
public static void RemoveAll<K, V>(this IDictionary<K, V> dict,
Func<K, V, bool> match)
    {
        foreach (var key in dict.Keys.ToArray()
            .Where(key => match(key, dict[key])))
            dict.Remove(key);
    }

AnswerRe: Faster Alternative? Pin
Michiel du Toit16-Nov-12 11:24
Michiel du Toit16-Nov-12 11:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.