RemoveAll Dictionary Extension Method

Removing from a dictionary all the elements where the keys satisfy a set of conditions is something I needed to do more than once so I implemented it as an extension method to the IDictionary<TKey, TValue> interface.

Here’s the code:

public static class DictionaryExtensions
{
    /// <summary>
    /// Removes all the elements where the key match the conditions defined by the specified predicate.
    /// </summary>
    /// <typeparam name="TKey">
    /// The type of the dictionary key.
    /// </typeparam>
    /// <typeparam name="TValue">
    /// The type of the dictionary value.
    /// </typeparam>
    /// <param name="dictionary">
    /// A dictionary from which to remove the matched keys.
    /// </param>
    /// <param name="match">
    /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the keys to remove.
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// dictionary is null
    /// <br />-or-<br />
    /// match is null.
    /// </exception>
    /// <returns>
    /// The number of elements removed from the <see cref="IDictionary{TKey, TValue}"/>.
    /// </returns>
    public static int RemoveAll<TKey, TValue>(
        this IDictionary<TKey, TValue> dictionary,
        Predicate<TKey> match)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

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

        var keysToRemove = dictionary.Keys.Where(k => match(k)).ToList();

        if (keysToRemove.Count == 0)
            return 0;

        foreach (var key in keysToRemove)
        {
            dictionary.Remove(key);
        }

        return keysToRemove.Count;
    }
}
Advertisements

One thought on “RemoveAll Dictionary Extension Method”

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