Menu
CoddyTech

Chỉnh sửa từ điển

Thuộc phần Logic và luồng chương trình trong hành trình C# của Coddy. Bài học 50 trên 66.

Từ điển trong C# có thể thay đổi, nghĩa là bạn có thể chỉnh sửa chúng sau khi tạo. Sau đây là những cách phổ biến để chỉnh sửa một từ điển:

Thêm một cặp khóa-giá trị mới:

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

Cập nhật giá trị của một khóa hiện có:

// Trước tiên, kiểm tra xem khóa có tồn tại không
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Cập nhật giá trị của "apple" thành 15
}

Xóa một cặp khóa-giá trị:

// Xóa mục "apple"
inventory.Remove("apple");

Xóa tất cả mục:

// Xóa tất cả các cặp khóa và giá trị
inventory.Clear();
challenge icon

Thử thách

Dễ

Tạo một phương thức có tên UpdateInventory nhận ba đối số:

  1. Một Dictionary<string, int> biểu thị kho hàng
  2. Một string biểu thị tên mặt hàng
  3. Một int biểu thị số lượng mới

Phương thức này cần:

  • Nếu mặt hàng đã có trong kho, cập nhật số lượng của mặt hàng đó
  • Nếu mặt hàng chưa có, thêm mặt hàng đó với số lượng đã cho
  • In kho hàng đã cập nhật theo định dạng: "Item: [quantity]" (mỗi mặt hàng trên một dòng)

Tự làm thử

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

class Program
{
    public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
    {
        // Viết code của bạn ở đây
        
        // In ra danh sách tồn kho sau khi cập nhật
        // Đừng xóa phần này
        foreach (KeyValuePair<string, int> entry in inventory)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
    // Bỏ qua code trong Main, phần này chuyển chuỗi thành HashMap
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Đọc dòng đầu tiên để kiểm tra định dạng JSON
        string firstLine = Console.ReadLine();
        
        // Kiểm tra xem đầu vào có ở định dạng JSON không
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Xử lý đầu vào JSON cho danh sách tồn kho ban đầu
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Tách theo dấu phẩy không nằm trong dấu ngoặc kép
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Dùng regex để trích xuất khóa và giá trị
                    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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch C# online