C# – Remove items from dictionary

Dictionaries contain key/value pairs. When you want to remove one or more items from a dictionary, you can use one of the following methods:

  • Use Dictionary.Remove() to remove an item by key.
  • Use Dictionary.Where() + Remove() to conditionally remove items based on key or value.
  • Use Dictionary.Clear() to remove all items.

I’ll show examples below.

Remove item by key

Use Dictionary.Remove() to remove an item based on its key. If the key exists, it removes the key/value pair from the dictionary and returns true. If the key doesn’t exist, it returns false. Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Linda"] = 2
};

bool bobRemoved = dictionary.Remove("Bob");
Console.WriteLine($"'Bob' was removed? {bobRemoved}");

bool teddyRemoved = dictionary.Remove("Teddy");
Console.WriteLine($"'Teddy' was removed? {teddyRemoved}");
Code language: C# (cs)

Note: In all examples, I’m initializing a dictionary with values and then showing how to remove them.

Because the ‘Bob’ key exists, this removed it and returned true. And because the ‘Teddy’ key doesn’t exist, there’s nothing to remove so it returned false. This example outputs the following:

'Bob' was removed? True
'Teddy' was removed? FalseCode language: plaintext (plaintext)

Notice that Dictionary.Remove() doesn’t throw an exception if the key doesn’t exist. That means you don’t need to bother checking if the key exists before calling Remove().

Note: If Remove() fails to remove an item unexpectedly, then you may have specified the string key with the wrong casing (i.e. ‘bob’ instead of ‘Bob’). If you need to be able to handle any casing, consider using a case insensitive dictionary.

Remove item(s) by value

You can remove items from the dictionary based on the value (or key) matching a condition. Do that by using Where() (Linq) to filter the items from the dictionary and remove them in a loop with Dictionary.Remove().

The most common use of this is removing items based on a specific value. Here’s an example:

using System.Linq;
using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Linda"] = 2,
    ["Teddy"] = 1
};

foreach(var kvp in dictionary.Where(t => t.Value == 1).ToList())
{
    dictionary.Remove(kvp.Key);
}

Console.WriteLine($"Dictionary now has {dictionary.Count} item");
Code language: C# (cs)

Note: I’m using .ToList() here to make this backward compatible with versions before .NET Core 3.0.

This removes the two items having a value of 1, leaving one item. This example outputs the following:

Dictionary now has 1 itemCode language: plaintext (plaintext)

You can use this approach to remove multiple items by key as well, but that’s not as common as removing multiple items based on a specific value.

Dictionary.RemoveAll() extension method

To simplify things, you can use the following RemoveAll() extension method. This does the same logic as the code shown above – it’s just a nice, reusable extension method:

using System.Linq;
using System.Collections.Generic;

public static class DictionaryExtensions
{
    public static void RemoveAll<TKey, TValue>(this Dictionary<TKey, TValue> dict, 
        Func<KeyValuePair<TKey,TValue>, bool> removeIf)
    {
        foreach(var item in dict.Where(removeIf).ToList())
        {
            dict.Remove(item.Key);
        }
    }
}
Code language: C# (cs)

Here’s two examples of using RemoveAll():

//Remove multiple items based on the value
dictionary.RemoveAll(t => t.Value == 1);

//Remove multiple items based on the key
dictionary.RemoveAll(t => t.Key.StartsWith("Bob"));
Code language: C# (cs)

Remove all items

Use Dictionary.Clear() to remove all keys from the dictionary:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Linda"] = 2
};

dictionary.Clear();

Console.WriteLine($"Dictionary count: {dictionary.Count}");
Code language: C# (cs)

This outputs the following:

Dictionary count: 0

Leave a Comment