nmgqww
Last Updated: February 25, 2016
·
554
· keboo

RemoveWhere extension method

Often we need to iterate over a collection and remove items that meat a given criteria. Sure List<T> has RemoveAll, but what about the cases where you do not have a List<T>?

Typically this results in code like the following:

var collection = new ObservableCollection<int> { 7, 2, 3, 4, 6, 5 };
var toRemove = collection.Where(x => x % 2 == 0).ToList();
foreach (var item in toRemove)
    collection.Remove(item);

Though there is nothing wrong with this, it means that we must first iterate over the collection, then go back and remove each item.

Here is an extension method that will do it in a single iteration:

private static void RemoveWhere<T>(IList<T> collection, Predicate<T> predicate)
{
    for (var i = collection.Count - 1; i >= 0; i--)
    {
        if (predicate(collection[i]))
        {
            collection.RemoveAt(i);
        }
    }
}

The basic idea is to iterate from the back of the list and only remove the items that match the given predicate and remove them.

This can be re-written to iterate forward over the list, however this requires that the variable i only be incremented when an item is not removed.

Source: http://dotnetgeek.tumblr.com/post/12585133935/remove-where-extension-method

Say Thanks
Respond

1 Response
Add your response

122
526113 624580858385 1044550908 n

I especially like the consolidation of the reverse iteration. I do that relatively often, and it always seems like more work to write the for loop.

over 1 year ago ·