查詢運算式中 orderby 位置靈活,不像 T-SQL 有嚴格順序限制。
var q = from e in db.Employees
orderby e.HireDate
select e;
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;
// 先依 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(c => c) 會拋例外OrderBy(c => new { c.City, c.ContactName }) 會拋例外
var q = db.Customers.Select(c => c.City).OrderBy(c => c).ToList(); // string 可排序
先 ToList() 取回記憶體,後續為 LINQ to Objects:
var q = db.Customers.ToList().OrderBy(c => c).ToList(); // 需 Customer 實作 IComparable
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged, IComparable {
public int CompareTo(Customer other) {
return this.CustomerID.CompareTo(other.CustomerID);
}
}
或使用非泛型 IComparable 需轉型。泛型版免轉型更安全。
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;
}
}