Collection RemoveAll Extension Method

I had previously posted a RemoveAll extension method for the Dictionary<K,V> class, now it’s time to have one for the Collection<T> class.

The signature is the same as in the corresponding method already available in List<T> and the implementation relies on the RemoveAt method to perform the actual removal of each element.

Finally, here’s the code:

public static class CollectionExtensions
    /// <summary>
    /// Removes from the target collection all elements that match the specified predicate.
    /// </summary>
    /// <typeparam name="T">The type of elements in the target collection.</typeparam>
    /// <param name="collection">The target collection.</param>
    /// <param name="match">The predicate used to match elements.</param>
    /// <exception cref="ArgumentNullException">
    /// The target collection is a null reference.
    /// <br />-or-<br />
    /// The match predicate is a null reference.
    /// </exception>
    /// <returns>Returns the number of elements removed.</returns>
    public static int RemoveAll<T>(this Collection<T> collection, Predicate<T> match)
        if (collection == null)
            throw new ArgumentNullException("collection");

        if (match == null)
            throw new ArgumentNullException("match");

        int count = 0;

        for (int i = collection.Count - 1; i >= 0; i--)
            if (match(collection[i]))

        return count;

One thought on “Collection RemoveAll Extension Method”

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s