首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

LINQ to SQL OrderBy 完整指南:排序語法、ThenBy 鏈式呼叫與自訂比較實作

     編輯:關於C#

基本排序語法

查詢運算式中 orderby 位置靈活,不像 T-SQL 有嚴格順序限制。

單一欄位升序(預設)


var q = from e in db.Employees
        orderby e.HireDate
        select e;

帶 Where 條件


var q = from o in db.Orders
        where o.ShipCity == "London"
        orderby o.Freight
        select o;
// where 與 orderby 順序可互換

降序


var q = from p in db.Products
        orderby p.UnitPrice descending
        select p;

多欄位排序:ThenBy 與 ThenByDescending

查詢運算式寫法


// 先依 City,再依 ContactName 升序
var q = from c in db.Customers
        orderby c.City, c.ContactName
        select c;

// 先依 ShipCountry 升序,再依 Freight 降序
var q = from o in db.Orders
        where o.EmployeeID == 1
        orderby o.ShipCountry, o.Freight descending
        select o;

方法語法(鏈式呼叫)


// ThenBy 級連
db.Customers.OrderBy(c => c.City).ThenBy(c => c.ContactName)

// 等價於逆序 OrderBy(注意順序相反)
db.Customers.OrderBy(c => c.ContactName).OrderBy(c => c.City)

// 降序版
db.Customers.OrderByDescending(c => c.City).ThenByDescending(c => c.ContactName)

關鍵:多重 OrderBy 鏈式呼叫時,主要排序鍵必須在最後呼叫。

OrderBy 限制

  • 不支援對完整型別排序:OrderBy(c => c) 會拋例外
  • 不支援對匿名型別排序:OrderBy(c => new { c.City, c.ContactName }) 會拋例外

正確做法:投影為基本型別再排序


var q = db.Customers.Select(c => c.City).OrderBy(c => c).ToList(); // string 可排序

LINQ to Objects 可支援型別排序(需實作 IComparable)

先 ToList() 取回記憶體,後續為 LINQ to Objects:


var q = db.Customers.ToList().OrderBy(c => c).ToList(); // 需 Customer 實作 IComparable

實作 IComparable 範例


public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged, IComparable {
    public int CompareTo(Customer other) {
        return this.CustomerID.CompareTo(other.CustomerID);
    }
}

或使用非泛型 IComparable 需轉型。泛型版免轉型更安全。

複合鍵比較:OrderDetail 先依 OrderID 再依 ProductID


public partial class OrderDetail : IComparable {
    public int CompareTo(OrderDetail other) {
        int k = this.OrderID - other.OrderID;
        if (k == 0) k = this.ProductID - other.ProductID;
        return k;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved