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

التحقق من وجود المفتاح

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

للتحقق مما إذا كان المفتاح موجوداً في HashMap (Dictionary في C#)، يمكنك استخدام الدالة ContainsKey().

أولاً، قم بإنشاء Dictionary:

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

أضف بعض أزواج المفتاح-القيمة:

ages.Add("John", 25);
ages.Add("Mary", 30);

الآن تحقق مما إذا كان المفتاح موجوداً:

bool exists = ages.ContainsKey("John");

بعد تنفيذ الكود أعلاه، سيكون المتغير exists هو true.

يمكنك استخدام هذا في جملة شرطية:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

التحدي

سهل

قم بإنشاء طريقة (method) تسمى CheckKeyExists تأخذ وسيطين (arguments):

  • قاموس من نوع Dictionary<string, int> (dictionary)
  • سلسلة نصية (string) (key) للتحقق منها

يجب أن تتحقق الطريقة مما إذا كان المفتاح موجوداً في القاموس وتطبع:

  • "Key exists" إذا تم العثور على المفتاح
  • "Key does not exist" إذا لم يتم العثور على المفتاح

ورقة مرجعية

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

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);

bool exists = ages.ContainsKey("John"); // يعيد true

الاستخدام في الجمل الشرطية:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}

جرّب بنفسك

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // اكتب الكود هنا
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = 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);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Reading the key to check directly
                string keyToCheck = Console.ReadLine();
                CheckKeyExists(inventory, keyToCheck);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            // Process original line-by-line format
            string line = firstLine;
            
            // Read lines until an empty line is entered
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    string[] parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        inventory.Add(parts[0], int.Parse(parts[1]));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error parsing line: {ex.Message}");
                }
                
                // Read next line
                line = Console.ReadLine();
            }
            
            // Reading the key to check
            string keyToCheck = Console.ReadLine();
            CheckKeyExists(inventory, keyToCheck);
        }
    }
}
quiz iconاختبر نفسك

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

جميع دروس Logic & Flow