Menu
Coddy logo textTech

Modifying Dictionaries

Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 50 / 66.

C# dilindeki Dictionary'ler değiştirilebilir, yani onları oluşturduktan sonra değiştirebilirsiniz. Bir Dictionary'yi değiştirmenin yaygın yolları şunlardır:

Yeni bir anahtar-değer çifti ekleyin:

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

Mevcut bir anahtarın değerini güncelleyin:

// Önce anahtarın var olup olmadığını kontrol edin
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // "apple"ı değer 15'e günceller
}

Bir anahtar-değer çifti kaldırın:

// "apple" girişini kaldır
inventory.Remove("apple");

Tüm girişleri temizle:

// Tüm anahtar-değer çiftlerini kaldır
inventory.Clear();
challenge icon

Görev

Kolay

UpdateInventory adında bir metot oluşturun ki üç argüman alsın:

  1. Envanteri temsil eden bir Dictionary<string, int>
  2. Bir öğe adını temsil eden bir string
  3. Yeni miktarı temsil eden bir int

Metot şunları yapmalıdır:

  • Eğer öğe envanterde varsa, miktarını güncelleyin
  • Eğer öğe mevcut değilse, verilen miktarla ekleyin
  • Güncellenmiş envanteri şu formatta yazdırın: "Item: [quantity]" (her öğe bir satırda)

Kopya kağıdı

C#'ta Sözlükler değiştirilebilir ve oluşturulduktan sonra değiştirilebilir.

Yeni bir anahtar-değer çifti ekleyin:

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

Mevcut bir anahtarın değerini güncelleyin:

// Önce anahtarın var olup olmadığını kontrol edin
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // "apple"ı 15 değerine günceller
}

Bir anahtar-değer çifti kaldırın:

// "apple" girişini kaldır
inventory.Remove("apple");

Tüm girişleri temizleyin:

// Tüm anahtar-değer çiftlerini kaldır
inventory.Clear();

Kendin dene

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

class Program
{
    public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
    {
        // Kodunuzu buraya yazın
        
        // Güncellenmiş envanteri yazdırın
        // Bunu kaldırmayın
        foreach (KeyValuePair<string, int> entry in inventory)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
    // Ana kodu yoksayın, string'i HashMap'e dönüştürür
    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 iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

Mantık & Akış bölümündeki tüm dersler