Menu
Coddy logo textTech

Verificare se esiste una chiave

Fa parte della sezione Logica e flusso del percorso C# di Coddy. Lezione 48 di 66.

Per verificare se una chiave esiste in una HashMap (Dictionary in C#), puoi usare il metodo ContainsKey().

Per prima cosa, crea un dizionario:

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

Aggiungi alcune coppie chiave-valore:

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

Ora verifica se esiste una chiave:

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

Dopo aver eseguito il codice precedente, la variabile exists sarà true.

Puoi usarlo in un'istruzione condizionale:

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

Sfida

Facile

Crea un metodo chiamato CheckKeyExists che accetti due argomenti:

  • Un Dictionary<string, int> (dizionario)
  • Una stringa (chiave) da controllare

Il metodo deve verificare se la chiave esiste nel dizionario e stampare:

  • "Key exists" se la chiave viene trovata
  • "Key does not exist" se la chiave non viene trovata

Provalo tu

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Scrivi il codice qui
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Lettura dell'input dell'inventario: accetta sia il formato JSON sia il formato riga per riga
        string firstLine = Console.ReadLine();
        
        // Verifica se l'input è in formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Elabora l'input JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Dividi in corrispondenza delle virgole che non si trovano tra virgolette
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Estrai la chiave e il valore 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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore C# online