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

دوال HashMap

جزء من قسم Logic & Flow في رحلة 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):

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");
// القاموس يحتوي الآن فقط على درجة 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> كوسيط (argument) وتقوم بالعمليات التالية:

  1. اطبع Keys: متبوعة بجميع المفاتيح (مفتاح واحد في كل سطر)
  2. اطبع Values: متبوعة بجميع القيم (قيمة واحدة في كل سطر)
  3. تحقق مما إذا كان القاموس يحتوي على المفتاح "total" واطبع Contains 'total': True أو Contains 'total': False
  4. قم بإزالة المفتاح "temp" إذا كان موجوداً
  5. اطبع Count: متبوعاً بعدد العناصر في القاموس بعد هذه العمليات (استخدم الخاصية .Count للقاموس)

ورقة مرجعية

تحقق مما إذا كان المفتاح موجوداً باستخدام ContainsKey():

bool hasKey = dictionary.ContainsKey("keyName");

الحصول على جميع المفاتيح من القاموس (dictionary):

Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
    Console.WriteLine(key);
}

الحصول على جميع القيم من القاموس (dictionary):

Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
    Console.WriteLine(value);
}

إزالة عنصر باستخدام Remove():

dictionary.Remove("keyName");

مسح جميع العناصر باستخدام Clear():

dictionary.Clear();

الحصول على عدد العناصر باستخدام .Count:

int count = dictionary.Count;

جرّب بنفسك

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

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // اكتب كودك هنا
    }
    // تجاهل الكود الرئيسي، فهو يقوم بتحويل string إلى 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اختبر نفسك

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

جميع دروس Logic & Flow