GroupBy باستخدام أكثر من مفتاح (Multiple Keys) في LINQ

GroupBy باستخدام أكثر من مفتاح (Multiple Keys) في LINQ

دالة GroupBy في LINQ مش لازم تشتغل على خاصية واحدة فقط، تقدر تستخدم مفتاح مركب يجمع أكتر من خاصية، زي Branch وGender مثلاً.



تعريف الكلاس:


public class Student
{
    public int StudentID { get; set; }
    public string Name { get; set; }
    public string Branch { get; set; }
    public string Gender { get; set; }
}


مصدر البيانات:


List<Student> studentList = new List<Student>()
{
    new Student() { StudentID = 1, Name = "John", Branch = "CSE", Gender = "Male"},
    new Student() { StudentID = 2, Name = "Moin", Branch = "CSE", Gender = "Male"},
    new Student() { StudentID = 3, Name = "Ram", Branch = "ECE", Gender = "Male"},
    new Student() { StudentID = 4, Name = "Sara", Branch = "CSE", Gender = "Female"},
    new Student() { StudentID = 5, Name = "Sania", Branch = "ECE", Gender = "Female"},
    new Student() { StudentID = 6, Name = "Ravi", Branch = "EEE", Gender = "Male"},
    new Student() { StudentID = 7, Name = "Anjali", Branch = "EEE", Gender = "Female"}
};


GroupBy باستخدام أكثر من مفتاح (Method Syntax):


var groupByMultipleKeys = studentList
    .GroupBy(s => new { s.Branch, s.Gender });

foreach (var group in groupByMultipleKeys)
{
    Console.WriteLine($"Branch: {group.Key.Branch}, Gender: {group.Key.Gender} - Count: {group.Count()}");
    foreach (var student in group)
    {
        Console.WriteLine($"  {student.Name}");
    }
}


GroupBy باستخدام أكثر من مفتاح (Query Syntax):


var groupByMultipleKeys = from student in studentList
                          group student by new { student.Branch, student.Gender } into studentGroup
                          select studentGroup;

foreach (var group in groupByMultipleKeys)
{
    Console.WriteLine($"Branch: {group.Key.Branch}, Gender: {group.Key.Gender} - Count: {group.Count()}");
    foreach (var student in group)
    {
        Console.WriteLine($"  {student.Name}");
    }
}


الناتج المتوقع:


Branch: CSE, Gender: Male - Count: 2  
  John  
  Moin  
Branch: ECE, Gender: Male - Count: 1  
  Ram  
Branch: CSE, Gender: Female - Count: 1  
  Sara  
Branch: ECE, Gender: Female - Count: 1  
  Sania  
Branch: EEE, Gender: Male - Count: 1  
  Ravi  
Branch: EEE, Gender: Female - Count: 1  
  Anjali  


ملاحظات هامة:

  • المفتاح هنا عبارة عن anonymous object فيه خاصيتين: Branch و Gender.
  • ينفع تستخدم group.Key.Branch و group.Key.Gender في أي عملية داخل الحلقة.
  • النتائج بتكون متجمعة حسب كل تركيبة من الخصائص.


تعليقات

المشاركات الشائعة من هذه المدونة

C# - Arrays

Entity Framework - ما هو ORM؟ ونبذة عن Dapper وNHibernate

Entity Framework - مقدمة عن Entity Framework