Menu
CoddyTech

修改字典

本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 50 课,共 66 课。

C# 中的字典是可变的,这意味着创建字典后,你可以对其进行修改。以下是修改 Dictionary 的常见方法:

添加一个新的键值对:

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

更新现有键的值:

// 先检查键是否存在
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // 将 "apple" 的值更新为 15
}

删除一个键值对:

// 移除 "apple" 条目
inventory.Remove("apple");

清除所有条目:

// 删除所有键值对
inventory.Clear();
challenge icon

挑战

简单

创建一个名为 UpdateInventory 的方法,它接受三个参数:

  1. 一个表示库存的 Dictionary<string, int>
  2. 一个表示物品名称的字符串
  3. 一个表示新数量的 int

该方法应当:

  • 如果库存中存在该物品,就更新它的数量
  • 如果库存中不存在该物品,就以给定的数量添加该物品
  • 按以下格式输出更新后的库存:"Item: [quantity]"(每行一个物品)

亲手试试

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

class Program
{
    public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
    {
        // 在这里编写你的代码
        
        // 打印更新后的 inventory
        // 不要删除这段代码
        foreach (KeyValuePair<string, int> entry in inventory)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
    // 忽略 main 代码,它会将字符串转换为 HashMap
    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
            {
                // 处理初始 inventory 的 JSON 输入
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // 按引号外的逗号拆分
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // 使用正则表达式提取键和值
                    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自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: C# 在线编译器