LINQ ThenBy and ThenByDescending Method

LINQ ThenBy و ThenByDescending


لما تستخدم OrderBy بترتب حسب خاصية واحدة. لكن لو عايز ترتب حسب أكتر من خاصية، تستخدم:

  • ThenBy للترتيب الثانوي التصاعدي.
  • ThenByDescending للترتيب الثانوي التنازلي.



🧩 مثال عملي: ترتيب الطلاب حسب الفرع ثم الاسم


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

List<Student> studentList = new List<Student>()
{
    new Student() { ID = 1, Name = "Mahmoud", Branch = "CSE" },
    new Student() { ID = 2, Name = "Ahmed", Branch = "CSE" },
    new Student() { ID = 3, Name = "Sara", Branch = "ECE" },
    new Student() { ID = 4, Name = "Ziad", Branch = "CSE" },
    new Student() { ID = 5, Name = "Laila", Branch = "ECE" }
};

var result = studentList
                .OrderBy(s => s.Branch)
                .ThenBy(s => s.Name);

foreach (var s in result)
{
    Console.WriteLine($"ID = {s.ID}, Name = {s.Name}, Branch = {s.Branch}");
}

📌 النتيجة: الترتيب حسب الفرع (CSE ثم ECE)، وكل فرع مترتب بالأسماء من A إلى Z.



✅ مثال: ترتيب ثانوي تنازلي باستخدام ThenByDescending


var result = studentList
                .OrderBy(s => s.Branch)
                .ThenByDescending(s => s.Name);

📌 هنا الأسماء في كل فرع هتترتب من Z لـ A.



✅ استخدام ThenBy مع Query Syntax


var result = from s in studentList
             orderby s.Branch, s.Name descending
             select s;

ملحوظة: الكلمة descending بتأثر على الخاصية اللي بعدها فقط.



💡 ملاحظات:

  • ThenBy لازم يتكتب بعد OrderBy.
  • تقدر تستخدم أكتر من ThenBy لو عندك ترتيب ثلاثي أو أكتر.
  • الترتيب بيتم بشكل هرمي: أول خاصية، ثم الثانية، ثم الثالثة...


تعليقات

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

C# - Arrays

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

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