Cho phép sắp xếp các phần tử trong một danh sách theo một hay vài điều điều kiện nào đó. Các toán tử thuộc nhóm sắp xếp (hay chọn) gồm:

Toán tử Mô tả Cú pháp C# Cú pháp VB
OrderBy Sắp xếp các giá trị theo thứ tự tăng dần orderby Order By
OrderByDescending Sắp xếp các giá trị theo thứ tự giảm dần orderby…

descending

Order By… Descending
ThenBy Sắp xếp phụ (sắp xếp bổ sung sau khi sắp xếp lần thứ nhất, ví dụ sắp xếp danh sách theo tên nhưng nếu tên trùng nhau thì sắp xếp theo năm sinh) các giá trị theo thứ tự tăng dần orderby…,…. Order By…,….
ThenByDescending Sắp xếp phụ (sắp xếp bổ sung sau khi sắp xếp lần thứ nhất, ví dụ sắp xếp danh sách theo tên nhưng nếu tên trùng nhau thì sắp xếp theo năm sinh) các giá trị theo thứ tự giảm dần orderby…,….

descending

Order By…,… Descending
Reverse Đảo thứ tự các phần tử trong danh sách Không hỗ trợ Không hỗ trợ

 

Ví dụ OrderBy và OrderByDescending với C#


int[] num = { -20, 12, 6, 10, 0, -3, 1 };

var posNums = from n in num

   orderby n

   select n;

Console.Write("Sắp xếp tăng dần: ");

foreach (int i in posNums)

    Console.Write(i + " \n");

var posNumsDesc = from n in num

      orderby n descending

      select n;

Console.Write("\nSắp xếp giảm dần: ");

foreach (int i in posNumsDesc)

   Console.Write(i + " \n");

Trong LINQPad

Ví dụ OrderBy và OrderByDescending với VB


Dim num As Integer() = {-20, 12, 6, 10, 0, -3, 1}

Dim posNums = From n In num

   Order By n

   Select n

Console.Write("Sắp xếp tăng dần: ")

For Each n In posNums

   Console.WriteLine(n)

Next

Dim posNumsDesc = From n In num

   Order By n Descending

   Select n

Console.Write("Sắp xếp giảm dần: ")

For Each n In posNumsDesc

  Console.WriteLine(n)

Next

Trong LINQPad

< Các toán tử truy vấn