A RemoveAll Extension for the Collection Class

For some reason the Collection<T> class doesn’t contain a number of methods found on the List<T> class. The fabulous extensibility in .Net makes it easy to overcome however. Here’s my suggestion for an extension method that will do the trick:

public static void RemoveAll<T>(this Collection<T> collection, Func<T,bool> condition)
    collection.Where<T>(condition).ToList().ForEach(e => collection.Remove(e));

The point here – as opposed to some other solutions I’ve seen – is to only create a temporary list of the objects to remove, assuming that there will be fewer of these than of the number of elements remaining, thus minimizing the overhead.

And a sample invocation:

var collection = new Collection<string>();


collection.RemoveAll(s => s.StartsWith("X"));

Posted in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s