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.
RemoveAll for any
IList<T> but does not do so for
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:
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])))
An example of using it:
var dictionary = new Dictionary<string, int>();
dictionary["A"] = 0;
dictionary["B"] = 1;
dictionary["C"] = 2;
dictionary["D"] = 3;
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.
- 2012/11/16 - Posted.
- 2012/11/17 - Updated with performance enhancement recommended by George Swan.
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).