Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

الوصول إلى القيم

جزء من قسم Logic & Flow في رحلة C# على Coddy — الدرس 49 من 66.

في لغة #C، نستخدم Dictionary<TKey, TValue> كالمكافئ لـ HashMap. بعد إضافة العناصر إلى Dictionary، ستحتاج إلى استرجاعها.

قم بإنشاء Dictionary بمفاتيح من نوع string وقيم من نوع 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> (dictionary).
  2. سلسلة نصية (key) للبحث عنها.

يجب أن تحاول الطريقة الوصول إلى القيمة الخاصة بالمفتاح المعطى و:

  • إذا كان المفتاح موجوداً، قم بطباعة القيمة.
  • إذا كان المفتاح غير موجود، قم بطباعة "Key not found".

ورقة مرجعية

أنشئ قاموساً (Dictionary) بمفاتيح من نوع string وقيم من نوع int:

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

أضف مدخلات إلى القاموس:

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

الوصول إلى قيمة باستخدام مفتاح:

int johnScore = studentScores["John"];

الوصول إلى مفتاح غير موجود سيؤدي إلى استثناء من نوع KeyNotFoundException:

// سيؤدي هذا إلى طرح استثناء إذا لم يكن "Bob" موجوداً في القاموس
int bobScore = studentScores["Bob"];

جرّب بنفسك

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اختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس Logic & Flow