The life of a code monkey

Text

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.  

Posted on Wednesday, November 9 2011. Tagged with: CExtension MethodEnumerableEnumeratorLINQ
13
Notes
  1. ballisticexd liked this
  2. dictionaryde2 liked this
  3. daughters45go liked this
  4. miscarriage8it liked this
  5. practicing90fg liked this
  6. mission09is liked this
  7. emileeyou89 liked this
  8. nickthejam liked this
  9. dotnetgeek posted this
Got a question or comment? Ask me.
Previous Next