.NET Framework Removing from a Dictionary


Example

Given this setup code:

var dict = new Dictionary<int, string>()
{
    { 1, "First" },
    { 2, "Second" },
    { 3, "Third" }
};

Use the Remove method to remove a key and its associated value.

bool wasRemoved = dict.Remove(2);

Executing this code removes the key 2 and it's value from the dictionary. Remove returns a boolean value indicating whether the specified key was found and removed from the dictionary. If the key does not exist in the dictionary, nothing is removed from the dictionary, and false is returned (no exception is thrown).

It's incorrect to try and remove a key by setting the value for the key to null.

dict[2] = null; // WRONG WAY TO REMOVE!

This will not remove the key. It will just replace the previous value with a value of null.

To remove all keys and values from a dictionary, use the Clear method.

dict.Clear();

After executing Clear the dictionary's Count will be 0, but the internal capacity remains unchanged.