Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

584
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda