How to remove a KEY from a dictionary in c#

Viewed 11287

I have a dictionary called d as mentioned.

Dictionary<string, int> d = new Dictionary<string, int>();
    d["dog"] = 1;
    d["cat"] = 5;

Now if I want to remove the key "cat" I cant use the Remove() method as it only removes the corresponding value associated and not the key itself. So is there a way to remove a key?

2 Answers

The Remove() method actually deletes an existing key-value pair from a dictionary. You can also use the clear method to delete all the elements of the dictionary.

var cities = new Dictionary<string, string>(){
    {"UK", "London, Manchester, Birmingham"},
    {"USA", "Chicago, New York, Washington"},
    {"India", "Mumbai, New Delhi, Pune"}
};

cities.Remove("UK"); // removes UK 
//cities.Remove("France"); //throws run-time exception: KeyNotFoundException

if(cities.ContainsKey("France")){ // check key before removing it
    cities.Remove("France");
}

cities.Clear(); //removes all elements

You can read this for more information https://www.tutorialsteacher.com/csharp/csharp-dictionary

The documentation is a bit unclear here, you are right:

Removes the value with the specified key from the Dictionary<TKey,TValue>.

If you scroll down a bit you see a better wording:

The following code example shows how to remove a key/value pair from a dictionary using the Remove method.

There is never a key without a value in a dictionary(even a null value would be a value). It is always a KeyValuePair<TKey, TValue>. So you can simply use Remove to remove the cat-entry.

d.Remove("cat"); // cat gone
Console.Write(d.Count); // 1
Related