Removing from a Dictionary
suggest changeGiven 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 its value from the dictionary. Remove returns a boolean value indicating whether the specified key was found and removed. If the key is not in the dictionary, nothing is removed 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents