Menu
Coddy logo textTech

Check If Key Exists

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

Чтобы проверить, существует ли ключ в HashMap (Dictionary в C#), вы можете использовать метод ContainsKey().

Сначала создайте словарь:

Dictionary<string, int> ages = new Dictionary<string, int>();

Добавьте несколько пар ключ-значение:

ages.Add("John", 25);
ages.Add("Mary", 30);

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

bool exists = ages.ContainsKey("John");

После выполнения приведённого выше кода переменная exists будет равна true.

Вы можете использовать это в условном операторе:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

Задание

Легко

Создайте метод с именем CheckKeyExists, который принимает два аргумента:

  • Dictionary<string, int> (dictionary)
  • string (key) для проверки

Метод должен проверить, существует ли ключ в словаре, и вывести:

  • "Key exists", если ключ найден
  • "Key does not exist", если ключ не найден

Шпаргалка

Чтобы проверить наличие ключа в Dictionary, используйте метод ContainsKey():

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);

bool exists = ages.ContainsKey("John"); // возвращает true

Использование в условных конструкциях:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}

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

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Напишите код здесь
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Чтение входных данных инвентаря — поддерживается как формат JSON, так и построчный формат
        string firstLine = Console.ReadLine();
        
        // Проверка, является ли ввод форматом JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Обработка ввода JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Разделение по запятым, которые не находятся внутри кавычек
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Извлечение ключа и значения с помощью 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);
                        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);
        }
    }
}
quiz iconПроверьте себя

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

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