// 升序 (默認)
var q = from e in db.Employees
orderby e.HireDate
select e;
// 降序
var q = from p in db.Products
orderby p.UnitPrice descending
select p;
LINQ 允許 where 在 orderby 前後任意位置,異於 T-SQL 固定順序。
var q = from o in db.Orders
where o.ShipCity == "London"
orderby o.Freight
select o;
orderby c.City, c.ContactName
var q = db.Customers
.OrderBy(c => c.City)
.ThenBy(c => c.ContactName);
注意:多個 OrderBy 串聯時按逆序生效 (最後調用的為主鍵)。
var q = db.Customers
.OrderByDescending(c => c.City)
.ThenByDescending(c => c.ContactName);
// 錯誤:拋出異常
.OrderBy(c => new { c.City, c.ContactName })
// 正確:先 Select 基本類型再排序
.Select(c => c.City)
.OrderBy(c => c);
var q = from p in db.Products
group p by p.CategoryID into g
orderby g.Key
select new {
g.Key,
MostExpensive = from p2 in g
where p2.UnitPrice == g.Max(p3 => p3.UnitPrice)
select p2
};
先分組,再按分組鍵排序,最後投影每組最高價產品。
| LINQ | T-SQL |
|---|---|
| OrderBy | ORDER BY col ASC |
| OrderByDescending | ORDER BY col DESC |
| ThenBy | ORDER BY col1, col2 |
| ThenByDescending | ORDER BY col1 DESC, col2 DESC |
OrderBy/ThenBy),可讀性更強OrderBy 必須在 Skip/Take 之前