Menu
Coddy logo textTech

מתודות של HashMap

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

השיטות של HashMap מספקות דרכים עוצמתיות לעבודה עם נתוני המילון שלך. בואו נבחן כמה שיטות נפוצות:

בדקו אם מפתח קיים במילון:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// הערך של hasApples יהיה true

קבלו את כל המפתחות מהמילון:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

// קבל את כל המפתחות
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
    Console.WriteLine(name);
}

קבל את כל הערכים מהמילון:

// קבל את כל הערכים
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

הסרת פריט מהמילון:

scores.Remove("Bob");
// Dictionary מכיל כעת רק את הניקוד של Alice

נקה את כל הפריטים:

scores.Clear();
// המילון ריק כעת

קבלו את מספר הפריטים במילון באמצעות .Count:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// פלט: 2
challenge icon

אתגר

בינוני

צור מתודה בשם ProcessDictionary שמקבלת Dictionary<string, int> כארגומנט ומבצעת את הפעולות הבאות:

  1. הדפס Keys: ואחריו את כל המפתחות (אחד בכל שורה)
  2. הדפס Values: ואחריו את כל הערכים (אחד בכל שורה)
  3. בדוק אם המילון מכיל את המפתח "total" והדפס Contains 'total': True או Contains 'total': False
  4. הסר את המפתח "temp" אם הוא קיים
  5. הדפס Count: ואחריו את מספר הפריטים במילון לאחר הפעולות האלה (השתמש במאפיין .Count של המילון)

נסו בעצמכם

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

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // כתבו את הקוד שלכם כאן
    }
    // התעלמו מהקוד הראשי, הוא ממיר מחרוזת ל-HashMap
    static void Main(string[] args)
    {
        Dictionary<string, int> inputDict = 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);
                        inputDict.Add(keyMatch, valueMatch);
                    }
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int n = int.Parse(firstLine);
                
                for (int i = 0; i < n; i++)
                {
                    string[] pair = Console.ReadLine().Split(':');
                    string key = pair[0];
                    int value = int.Parse(pair[1]);
                    inputDict.Add(key, value);
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconבחנו את עצמכם

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

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

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