Menu
CoddyTech

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

جزء من قسم المنطق وتدفق التنفيذ في رحلة C# على Coddy. الدرس 49 من 66.

في C#، نستخدم Dictionary<TKey, TValue> بوصفه النظير لـ HashMap. بعد إضافة عناصر إلى 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. قاموسًا من النوع <string, int> (dictionary).
  2. سلسلة نصية (key) للبحث عنها.

ينبغي للدالة أن تحاول الوصول إلى القيمة الخاصة بالمفتاح المحدد، وأن:

  • إذا كان المفتاح موجودًا، فاطبع القيمة.
  • إذا لم يكن المفتاح موجودًا، فاطبع "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)
                    {
                        // استخرج المفتاح والقيمة باستخدام التعبيرات النمطية
                        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# عبر الإنترنت