Menu
Coddy logo textTech

HashMap Methods

Часть раздела Логика и управление потоком путешествия по C# на Coddy — урок 52 из 66.

Методы HashMap предоставляют мощные способы работы с вашими данными словаря. Давайте рассмотрим некоторые распространённые методы:

Проверить, существует ли ключ в словаре:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// hasApples will be true

Получить все ключи из словаря:

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);
}

Получить все значения из словаря:

// Get all values
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

Удалить элемент из словаря:

scores.Remove("Bob");
// Dictionary now only contains Alice's score

Очистить все элементы:

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

Получите количество элементов в словаре с помощью .Count:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// Output: 2
challenge icon

Задание

Средне

Создайте метод с именем ProcessDictionary, который принимает Dictionary<string, int> в качестве аргумента и выполняет следующие операции:

  1. Выведите Keys: за которым следуют все ключи (по одному на строку)
  2. Выведите Values: за которым следуют все значения (по одному на строку)
  3. Проверьте, содержит ли словарь ключ "total", и выведите Contains 'total': True или Contains 'total': False
  4. Удалите ключ "temp", если он существует
  5. Выведите Count: за которым следует количество элементов в словаре после этих операций (используйте свойство .Count словаря)

Шпаргалка

Проверьте наличие ключа с помощью ContainsKey():

bool hasKey = dictionary.ContainsKey("keyName");

Получите все ключи из словаря:

Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
    Console.WriteLine(key);
}

Получите все значения из словаря:

Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
    Console.WriteLine(value);
}

Удалите элемент с помощью Remove():

dictionary.Remove("keyName");

Очистите все элементы с помощью Clear():

dictionary.Clear();

Получите количество элементов с помощью .Count:

int count = dictionary.Count;

Попробуйте сами

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // Напишите свой код здесь
    }
    // Игнорируйте основной код, он преобразует строку в 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 iconПроверьте себя

В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.

Все уроки раздела Логика и управление потоком