Menu
Coddy logo textTech

Modifying Dictionaries

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

Словари в C# изменяемы, что означает, что вы можете изменять их после их создания. Вот распространённые способы изменения Dictionary:

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

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);

Обновить значение существующего ключа:

// First check if key exists
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Updates "apple" to have value 15
}

Удалить пару ключ-значение:

// Remove the "apple" entry
inventory.Remove("apple");

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

// Remove all key-value pairs
inventory.Clear();
challenge icon

Задание

Легко

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

  1. Dictionary<string, int>, представляющий инвентарь
  2. строку, представляющую название предмета
  3. целое число, представляющее новое количество

Метод должен:

  • Если предмет существует в инвентаре, обновить его количество
  • Если предмет не существует, добавить его с указанным количеством
  • Вывести обновленный инвентарь в формате: "Item: [quantity]" (по одному предмету на строку)

Шпаргалка

Словари в C# изменяемы и могут быть модифицированы после создания.

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

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);

Обновить значение существующего ключа:

// First check if key exists
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Updates "apple" to have value 15
}

Удалить пару ключ-значение:

// Remove the "apple" entry
inventory.Remove("apple");

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

// Remove all key-value pairs
inventory.Clear();

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

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

class Program
{
    public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
    {
        // Напишите свой код здесь
        
        // Вывести обновленный инвентарь
        // Не удаляйте это
        foreach (KeyValuePair<string, int> entry in inventory)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
    // Игнорируйте основной код, он преобразует строку в HashMap
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = 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 for initial inventory
                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);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Read the item to update and its quantity
                string updateItemJson = Console.ReadLine();
                // Check if update item is in JSON format with quotes
                Match itemMatch = Regex.Match(updateItemJson, @"""([^""]+)""");
                string updateItem = itemMatch.Success ? itemMatch.Groups[1].Value : updateItemJson;
                
                int updateQuantity = int.Parse(Console.ReadLine());
                
                UpdateInventory(inventory, updateItem, updateQuantity);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int initialCount = int.Parse(firstLine);
                for (int i = 0; i < initialCount; i++)
                {
                    string item = Console.ReadLine();
                    int quantity = int.Parse(Console.ReadLine());
                    inventory.Add(item, quantity);
                }
                
                // Read the item to update and its quantity
                string updateItem = Console.ReadLine();
                int updateQuantity = int.Parse(Console.ReadLine());
                
                UpdateInventory(inventory, updateItem, updateQuantity);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconПроверьте себя

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

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