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Задание
СреднеСоздайте метод с именем ProcessDictionary, который принимает Dictionary<string, int> в качестве аргумента и выполняет следующие операции:
- Выведите
Keys:за которым следуют все ключи (по одному на строку) - Выведите
Values:за которым следуют все значения (по одному на строку) - Проверьте, содержит ли словарь ключ
"total", и выведитеContains 'total': TrueилиContains 'total': False - Удалите ключ
"temp", если он существует - Выведите
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}");
}
}
}
}В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.
Все уроки раздела Логика и управление потоком
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