Menu
Coddy logo textTech

Modifying Dictionaries

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 50/66。

C# の Dictionary は変更可能で、作成した後にそれらを変更できます。Dictionary を変更する一般的な方法を以下に示します:

新しいキー-値ペアを追加:

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

既存のキーの値を更新:

// まずキーの存在を確認
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // "apple" を値 15 に更新
}

キー値ペアを削除:

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

すべてのエントリをクリア:

// すべてのキー-値ペアを削除
inventory.Clear();
challenge icon

チャレンジ

簡単

UpdateInventory という名前のメソッドを作成し、3つの引数を受け取ります:

  1. インベントリを表す Dictionary<string, int>
  2. アイテム名を表す string
  3. 新しい数量を表す int

このメソッドは次のことを行うべきです:

  • アイテムがインベントリに存在する場合、その数量を更新します
  • アイテムが存在しない場合、指定された数量で追加します
  • 更新されたインベントリをフォーマット「"Item: [quantity]"」(1行に1アイテム)で出力します

チートシート

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();

自分で試してみよう

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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン