Menu
CoddyTech

دوال 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 فقط

تُرجع Remove() القيمة true إذا كان المفتاح موجودًا وأُزيل، والقيمة false إذا لم يكن موجودًا. لا يُعدّ حذف مفتاح غير موجود خطأً.

امسح جميع العناصر:

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# عبر الإنترنت