Menu
Coddy logo textTech

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 sein

Alle 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 Punktzahl

Alle Elemente löschen:

scores.Clear();
// Dictionary is now empty

Die 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: 2
challenge icon

Aufgabe

Mittel

Erstellen Sie eine Methode namens ProcessDictionary, die ein Dictionary<string, int> als Argument nimmt und die folgenden Operationen ausführt:

  1. Geben Sie Keys: aus gefolgt von allen Schlüsseln (einer pro Zeile)
  2. Geben Sie Values: aus gefolgt von allen Werten (einer pro Zeile)
  3. Überprüfen Sie, ob das Dictionary den Schlüssel "total" enthält, und geben Sie Contains 'total': True oder Contains 'total': False aus
  4. Entfernen Sie den Schlüssel "temp", falls er existiert
  5. 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}");
            }
        }
    }
}
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