Menu
Coddy logo textTech

Check If Key Exists

Teil des Abschnitts Logik & Ablauf der C#-Journey von Coddy — Lektion 48 von 66.

Um zu prüfen, ob ein Schlüssel in einer HashMap (Dictionary in C#) existiert, können Sie die ContainsKey()-Methode verwenden.

Zuerst ein Dictionary erstellen:

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

Fügen Sie einige Schlüssel-Wert-Paare hinzu:

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

Überprüfen Sie nun, ob ein Schlüssel existiert:

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

Nach der Ausführung des obigen Codes wird die Variable exists true sein.

Sie können dies in einer bedingten Anweisung verwenden:

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

Aufgabe

Einfach

Erstellen Sie eine Methode namens CheckKeyExists, die zwei Argumente annimmt:

  • Ein Dictionary<string, int> (dictionary)
  • Ein string (key) zur Überprüfung

Die Methode sollte prüfen, ob der Schlüssel im Dictionary existiert, und ausgeben:

  • "Key exists", wenn der Schlüssel gefunden ist
  • "Key does not exist", wenn der Schlüssel nicht gefunden ist

Spickzettel

Um zu prüfen, ob ein Schlüssel in einem Dictionary existiert, verwenden Sie die ContainsKey()-Methode:

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

bool exists = ages.ContainsKey("John"); // gibt true zurück

Verwendung in Bedingungsanweisungen:

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

Probier es selbst

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Schreibe den Code hier
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Einlesen der Inventareingabe - akzeptiert sowohl das JSON-Format als auch das zeilenweise Format
        string firstLine = Console.ReadLine();
        
        // Prüfen, ob die Eingabe im JSON-Format vorliegt
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // JSON-Eingabe verarbeiten
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // An Kommas trennen, die nicht innerhalb von Anführungszeichen stehen
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Schlüssel und Wert mittels regex extrahieren
                    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 iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Logik & Ablauf