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

HashMap متداخل

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

إن الـ HashMap المتداخل هو عبارة عن HashMap تكون فيه القيم نفسها عبارة عن HashMaps. وهذا مفيد لتنظيم البيانات الهرمية.

قم بإنشاء HashMap متداخلة لتخزين درجات الطلاب حسب المادة:

// إنشاء الـ HashMap الخارجية (الطالب -> المواد)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// إنشاء HashMap داخلية لطالب (المادة -> الدرجة)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// إضافة الدرجات إلى الـ HashMap الداخلية
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// إضافة الـ HashMap الداخلية إلى الـ HashMap الخارجية
studentGrades.Add("Alex", alexGrades);

الوصول إلى قيمة متداخلة:

// الوصول إلى درجة الرياضيات لـ Alex
int mathGrade = studentGrades["Alex"]["Math"]; // يعيد 90

أضف طالباً آخر مع درجاته:

// إنشاء HashMap داخلي آخر
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// الإضافة إلى HashMap الخارجي
studentGrades.Add("Sarah", sarahGrades);
challenge icon

التحدي

متوسط

أنشئ دالة باسم AddCourseGrade تأخذ أربعة وسائط:

  1. قاموس متداخل (nested Dictionary) يمثل درجات الطلاب: Dictionary<string, Dictionary<string, int>> grades
  2. اسم طالب (string)
  3. اسم دورة (string)
  4. درجة (int)

يجب أن تقوم الدالة بـ:

  • إذا لم يكن الطالب موجوداً في القاموس، فقم بإنشاء إدخال جديد له
  • أضف الدورة والدرجة إلى سجل الطالب
  • إذا كانت الدورة موجودة بالفعل لذلك الطالب، فقم بتحديث الدرجة
  • اطبع "Added [course] grade for [student]: [grade]" بعد الإضافة/التحديث

ورقة مرجعية

الـ HashMap المتداخل هو عبارة عن HashMap تكون القيم فيه هي نفسها HashMaps، وهو مفيد لتنظيم البيانات الهرمية.

إنشاء HashMap متداخل:

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

// إنشاء HashMap داخلي
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// الإضافة إلى الـ HashMap الخارجي
studentGrades.Add("Alex", alexGrades);

الوصول إلى القيم المتداخلة:

int mathGrade = studentGrades["Alex"]["Math"]; // يعيد 90

إضافة إدخال آخر:

Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
studentGrades.Add("Sarah", sarahGrades);

جرّب بنفسك

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

class Program
{
    public static void AddCourseGrade(Dictionary<string, Dictionary<string, int>> grades, string student, string course, int grade)
    {
        // اكتب كودك هنا
    }
    
    // تجاهل الكود الرئيسي، فهو يقوم بتحويل string إلى HashMap
    static void Main(string[] args)
    {
        // تحقق مما إذا كان السطر الأول قد يكون JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // مدخلات بتنسيق JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // تحليل درجات الطلاب الموجودة من JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                string studentPattern = @"""([^""]+)""\s*:\s*\{([^\}]+)\}";
                
                MatchCollection studentMatches = Regex.Matches(jsonContent, studentPattern);
                foreach (Match studentMatch in studentMatches)
                {
                    string studentName = studentMatch.Groups[1].Value;
                    string coursesJson = studentMatch.Groups[2].Value;
                    
                    Dictionary<string, int> courseGrades = new Dictionary<string, int>();
                    string coursePattern = @"""([^""]+)""\s*:\s*(\d+)";
                    
                    MatchCollection courseMatches = Regex.Matches(coursesJson, coursePattern);
                    foreach (Match courseMatch in courseMatches)
                    {
                        string courseName = courseMatch.Groups[1].Value;
                        int courseGrade = int.Parse(courseMatch.Groups[2].Value);
                        courseGrades.Add(courseName, courseGrade);
                    }
                    
                    studentGrades.Add(studentName, courseGrades);
                }
                
                // Parse student, course, and grade for the operation
                string studentInput = Console.ReadLine();
                Match studentNameMatch = Regex.Match(studentInput, @"""([^""]+)""");
                student = studentNameMatch.Success ? studentNameMatch.Groups[1].Value : studentInput;
                
                string courseInput = Console.ReadLine();
                Match courseNameMatch = Regex.Match(courseInput, @"""([^""]+)""");
                course = courseNameMatch.Success ? courseNameMatch.Groups[1].Value : courseInput;
                
                grade = int.Parse(Console.ReadLine());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // Traditional input
                student = firstLine;
                course = Console.ReadLine();
                grade = int.Parse(Console.ReadLine());
                
                // Create an example entry
                Dictionary<string, int> johnGrades = new Dictionary<string, int>();
                johnGrades.Add("Math", 88);
                studentGrades.Add("John", johnGrades);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing traditional input: {ex.Message}");
                return;
            }
        }
        
        AddCourseGrade(studentGrades, student, course, grade);
    }
}
quiz iconاختبر نفسك

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

جميع دروس Logic & Flow