ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Remove

Removes items from a list based on a condition you provide. I have a feeling this should exist already but I can't find it. You can get the same results using 'where' but this method operates on the collection itself.

Source

public static void Remove<T>(this ICollection<T> list, Func<T, bool> predicate)
{
    var items = list.Where(predicate).ToList();

    foreach (var item in items)
    {
        list.Remove(item);
    }
}

Example

var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

numbers.Remove(x => x > 5);

Author: Chris Meijers

Submitted on: 25 okt. 2010

Language: C#

Type: System.Collections.Generic.ICollection<T>

Views: 6381