Menu
Coddy logo textTech

גישה לערכים

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

ב־C#, משתמשים ב־Dictionary<TKey, TValue> כמקבילה ל־HashMap. לאחר הוספת פריטים ל־Dictionary, יהיה עליך לאחזר אותם.

צרו מילון עם מפתחות מסוג מחרוזת וערכים מסוג int:

Dictionary<string, int> studentScores = new Dictionary<string, int>();

הוסף כמה ערכים:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

גישה לערך באמצעות מפתח:

int johnScore = studentScores["John"];

לאחר הרצת הקוד שלמעלה, johnScore מכיל:

95

היזהר! אם תנסה לגשת למפתח שאינו קיים, תקבל חריגת KeyNotFoundException:

// פעולה זו תזרוק חריגה אם "Bob" לא נמצא במילון
int bobScore = studentScores["Bob"];
challenge icon

אתגר

קל

צרו מתודה בשם GetValueByKey שמקבלת שני ארגומנטים:

  1. מילון מסוג Dictionary<string, int> (מילון).
  2. מחרוזת (מפתח) לחיפוש.

על המתודה לנסות לגשת לערך של המפתח הנתון, ולפעול כך:

  • אם המפתח קיים, הדפיסו את הערך.
  • אם המפתח לא קיים, הדפיסו "Key not found".

נסו בעצמכם

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

class Program
{
    public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
    {
        // כתבו כאן קוד
    }
    
    static void Main(string[] args)
    {
        // קראו מילון בפורמט JSON: {"key1":value1,"key2":value2}
        string dictionaryInput = Console.ReadLine();
        string key = Console.ReadLine();
        
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        
        // נתחו את מחרוזת הקלט כדי ליצור מילון
        if (!string.IsNullOrEmpty(dictionaryInput))
        {
            try
            {
                // בדקו אם הקלט הוא בפורמט JSON
                if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
                {
                    // הסירו את הסוגריים המסולסלים
                    string jsonContent = dictionaryInput.Substring(1, dictionaryInput.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);
                            dictionary.Add(keyMatch, valueMatch);
                        }
                    }
                }
                // Handle the original format "key1:value1,key2:value2" as fallback
                else
                {
                    string[] pairs = dictionaryInput.Split(',');
                    foreach (string pair in pairs)
                    {
                        string[] keyValue = pair.Split(':');
                        if (keyValue.Length == 2)
                        {
                            dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
                        }
                    }
                }
                
                GetValueByKey(dictionary, key);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconבחנו את עצמכם

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

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

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