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();Задание
ЛегкоСоздайте метод с именем UpdateInventory, который принимает три аргумента:
- Dictionary<string, int>, представляющий инвентарь
- строку, представляющую название предмета
- целое число, представляющее новое количество
Метод должен:
- Если предмет существует в инвентаре, обновить его количество
- Если предмет не существует, добавить его с указанным количеством
- Вывести обновленный инвентарь в формате: "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}");
}
}
}
}В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.
Все уроки раздела Логика и управление потоком
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 Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap