Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a KEY from a dictionary in C#

Tags:

c#

dictionary

key

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 can't 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?

like image 229
Angad Khurana Avatar asked Sep 10 '25 18:09

Angad Khurana


1 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"); //will NOT throw a an exception when key `France` is not found.
//cities.Remove(null); //will throw an ArgumentNullException

}

cities.Clear(); //removes all elements

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

like image 61
Cyril Ikelie Avatar answered Sep 12 '25 07:09

Cyril Ikelie