Menu
Coddy logo textTech

Check If Key Exists

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 48 de 66.

Para comprobar si una clave existe en un HashMap (Dictionary en C#), puedes usar el método ContainsKey().

Primero, crea un Dictionary:

Dictionary<string, int> ages = new Dictionary<string, int>();

Añade algunos pares clave-valor:

ages.Add("John", 25);
ages.Add("Mary", 30);

Ahora verifica si existe una clave:

bool exists = ages.ContainsKey("John");

Después de ejecutar el código anterior, la variable exists será true.

Puedes usar esto en una instrucción condicional:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

Desafío

Fácil

Crea un método llamado CheckKeyExists que tome dos argumentos:

  • Un Dictionary<string, int> (dictionary)
  • Una string (key) para verificar

El método debe verificar si la clave existe en el diccionario e imprimir:

  • "Key exists" si se encuentra la clave
  • "Key does not exist" si no se encuentra la clave

Hoja de referencia

Para comprobar si una clave existe en un Dictionary, use el método ContainsKey():

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);

bool exists = ages.ContainsKey("John"); // returns true

Uso en sentencias condicionales:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}

Pruébalo tú mismo

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Escribe el código aquí
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Leyendo la entrada del inventario - acepta tanto el formato JSON como el formato línea por línea
        string firstLine = Console.ReadLine();
        
        // Comprueba si la entrada está en formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Procesar la entrada JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Dividir por comas que no estén dentro de comillas
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extraer la clave y el valor usando regex
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Reading the key to check directly
                string keyToCheck = Console.ReadLine();
                CheckKeyExists(inventory, keyToCheck);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            // Process original line-by-line format
            string line = firstLine;
            
            // Read lines until an empty line is entered
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    string[] parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        inventory.Add(parts[0], int.Parse(parts[1]));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error parsing line: {ex.Message}");
                }
                
                // Read next line
                line = Console.ReadLine();
            }
            
            // Reading the key to check
            string keyToCheck = Console.ReadLine();
            CheckKeyExists(inventory, keyToCheck);
        }
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo