Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

577
Views
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 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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!