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");
}Aufgabe
EinfachErstellen 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ückVerwendung 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);
}
}
}Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.
Alle Lektionen in Logik & Ablauf
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap