Search code examples
c#dictionarykey

How to remove a KEY from a dictionary in C#


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?


Solution

  • 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