Menu
Coddy logo textTech

שינוי מילונים

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-C# של Coddy. שיעור 50 מתוך 66.

מילונים ב-C# ניתנים לשינוי, כלומר אפשר לשנות אותם לאחר יצירתם. הנה הדרכים הנפוצות לשינוי מילון:

הוסיפו זוג מפתח-ערך חדש:

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)
    {
        // כתבו את הקוד שלכם כאן
        
        // הדפיסו את המלאי המעודכן
        // אל תסירו את זה
        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>();
        
        // קראו את השורה הראשונה כדי לבדוק אם היא בפורמט JSON
        string firstLine = Console.ReadLine();
        
        // בדקו אם הקלט בפורמט JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // עבדו את קלט ה-JSON עבור המלאי ההתחלתי
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // פצלו לפי פסיקים שאינם בתוך מרכאות
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // חלצו מפתח וערך באמצעות 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בחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר C# אונליין