C# Remove items from dictionary

By FoxLearn 1/21/2025 7:04:26 AM   23
Dictionaries store key/value pairs. To remove one or more items from a dictionary, you can use the following methods:
  • Use Dictionary.Remove() to delete an item by its key.
  • Use Dictionary.Where() in combination with Remove() to conditionally remove items based on the key or value.
  • Use Dictionary.Clear() to remove all items from the dictionary.

Remove item by key

You can use Dictionary.Remove() to remove an item by its key. If the key exists, it removes the key/value pair and returns true; if the key doesn't exist, it returns false.

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Alice"] = 10,
    ["John"] = 20
};

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

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

Since the key 'Alice' exists, it is removed, and true is returned. Since the key 'Jack' doesn't exist, it returns false because there is nothing to remove. The output will be:

'Alice' was removed? True
'Jack' was removed? False

Notice that Dictionary.Remove() does not throw an exception if the key doesn’t exist, so there’s no need to check for the key before calling Remove().

If Remove() fails unexpectedly, it might be due to a case mismatch in the key (e.g., 'alice' instead of 'Alice'). If you need case-insensitive handling, consider using a case-insensitive dictionary.

Remove item(s) by value

You can remove items based on the value (or key) by using Where() (LINQ) to filter items and remove them in a loop using Dictionary.Remove().

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

var dictionary = new Dictionary<string, int>()
{
    ["Alice"] = 10,
    ["John"] = 20,
    ["Sarah"] = 10
};

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

Console.WriteLine($"Dictionary now has {dictionary.Count} item(s)");

Note: .ToList() is used here for backward compatibility with versions before .NET Core 3.0.

This removes the two items with a value of 10, leaving only the item with a value of 20.

Output:

Dictionary now has 1 item(s)

Dictionary.RemoveAll() extension method

To simplify things, you can use the following RemoveAll() extension method, which implements the same logic as the previous example but in a reusable manner:

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);
        }
    }
}

For example, using RemoveAll():

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

// Remove multiple items based on key
dictionary.RemoveAll(t => t.Key.StartsWith("A"));

Remove all items

To remove all key/value pairs from a dictionary, use Dictionary.Clear():

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Alice"] = 10,
    ["John"] = 20
};

dictionary.Clear();

Console.WriteLine($"Dictionary count: {dictionary.Count}");

Output:

Dictionary count: 0