HashMap Methods
Teil des Abschnitts Logik & Ablauf der C#-Journey von Coddy — Lektion 52 von 66.
HashMap-Methoden bieten leistungsstarke Möglichkeiten, mit Ihren Wörterbuchdaten zu arbeiten. Lassen Sie uns einige gängige Methoden erkunden:
Prüfen, ob ein Schlüssel im Dictionary existiert:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);
bool hasApples = inventory.ContainsKey("apples");
// hasApples wird true seinAlle Schlüssel aus dem Dictionary abrufen:
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
// Get all keys
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
Console.WriteLine(name);
}Alle Werte aus dem Dictionary abrufen:
// Get all values
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
Console.WriteLine(score);
}Ein Element aus dem Dictionary entfernen:
scores.Remove("Bob");
// Dictionary enthält jetzt nur noch Alices PunktzahlAlle Elemente löschen:
scores.Clear();
// Dictionary is now emptyDie Anzahl der Elemente im Dictionary mit .Count ermitteln:
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
int total = scores.Count;
Console.WriteLine(total);
// Ausgabe: 2Aufgabe
MittelErstellen Sie eine Methode namens ProcessDictionary, die ein Dictionary<string, int> als Argument nimmt und die folgenden Operationen ausführt:
- Geben Sie
Keys:aus gefolgt von allen Schlüsseln (einer pro Zeile) - Geben Sie
Values:aus gefolgt von allen Werten (einer pro Zeile) - Überprüfen Sie, ob das Dictionary den Schlüssel
"total"enthält, und geben SieContains 'total': TrueoderContains 'total': Falseaus - Entfernen Sie den Schlüssel
"temp", falls er existiert - Geben Sie
Count:aus gefolgt von der Anzahl der Elemente im Dictionary nach diesen Operationen (verwenden Sie die.Count-Eigenschaft des Dictionarys)
Spickzettel
Prüfen, ob ein Schlüssel existiert, mit ContainsKey():
bool hasKey = dictionary.ContainsKey("keyName");Alle Schlüssel aus einem Dictionary abrufen:
Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
Console.WriteLine(key);
}Alle Werte aus einem Dictionary abrufen:
Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
Console.WriteLine(value);
}Ein Element mit Remove() entfernen:
dictionary.Remove("keyName");Alle Elemente mit Clear() löschen:
dictionary.Clear();Die Anzahl der Elemente mit .Count abrufen:
int count = dictionary.Count;Probier es selbst
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
static void ProcessDictionary(Dictionary<string, int> dict)
{
// Schreiben Sie Ihren Code hier
}
// Ignorieren Sie den Hauptcode, er konvertiert String zu einem HashMap
static void Main(string[] args)
{
Dictionary<string, int> inputDict = new Dictionary<string, int>();
// Read first line to check if it's JSON format
string firstLine = Console.ReadLine();
// Check if input is in JSON format
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// Process JSON input
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// Split by commas that are not inside quotes
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// Extract key and value using 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);
inputDict.Add(keyMatch, valueMatch);
}
}
ProcessDictionary(inputDict);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
else
{
try
{
// Process traditional input format
int n = int.Parse(firstLine);
for (int i = 0; i < n; i++)
{
string[] pair = Console.ReadLine().Split(':');
string key = pair[0];
int value = int.Parse(pair[1]);
inputDict.Add(key, value);
}
ProcessDictionary(inputDict);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
}
}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 Safety