Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Mệnh đề orderby trong LINQ C#


Giới thiệu

Mệnh đề orderby trong LINQ query syntax sắp xếp kết quả query theo một hoặc nhiều khóa, tăng dần (ascending - mặc định) hoặc giảm dần (descending).

Ví dụ cơ bản

List myList = new List { "iOS by Apple", "Android by Google", "Symbian by Nokia" };
var myLen = from element in myList
            orderby element.Length descending
            select element;

Ví dụ hoàn chỉnh

using System;
using System.Collections.Generic;
using System.Linq;

class Demo
{
    static void Main()
    {
        List myList = new List
        {
            "iOS by Apple",
            "Android by Google",
            "Symbian by Nokia"
        };

        var myLen = from element in myList
                    orderby element.Length descending
                    select element;

        Console.WriteLine("Descending order...");
        foreach (string str in myLen) Console.WriteLine(str);
    }
}

Kết quả

Descending order...
Android by Google
Symbian by Nokia
iOS by Apple

Sắp xếp đa khóa (ThenBy)

var sorted = from p in people
             orderby p.LastName, p.FirstName
             select p;
// Tương đương: people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName)

So sánh Query Syntax vs Method Syntax

Query SyntaxMethod Syntax
orderby x.NameOrderBy(x => x.Name)
orderby x.Name descendingOrderByDescending(x => x.Name)
orderby x.Age, x.NameOrderBy(x => x.Age).ThenBy(x => x.Name)

Lưu ý

  • Sắp xếp ổn định (stable) - phần tử bằng nhau giữ thứ tự gốc.
  • Deferred execution - sắp xếp thực thi khi enumerate (foreach, ToList, ...).
  • Null trong key: ném NullReferenceException nếu key selector trả null cho reference type. Dùng x?.Property ?? default.