LINQ - ThenBy、ThenByDescending
上一篇【Generic List Sorting in C# 3.0】講到只要有繼承 IEnumerable 介面或是 IEnumerable<T> 介面,現在都內建 OrderBy 與 OrderByDescending 的 Extension Methods 新功能。但是如果該欄位的值相等,要繼續比較其他的指定欄位,就需要 ThenBy、ThenByDescending 囉。
(1) 一樣建立 Product 類別作為示範,該類別擁有 int 型態的 ID 屬性、string 型態的 Name 屬性、double 型態的 Pricce 屬性、DateTime 型態的 ShipDate 屬性,覆寫 ToString() 方法方便我們列印。
(2) 利用 Collection Initializers 建立實例
1: var pList = new List<Product>
2: {
3: new Product {ID = 1, Name = "A", Price = 19, ShipDate = new DateTime(2006, 1, 19)},
4: new Product {ID = 7, Name = "C", Price = 17, ShipDate = new DateTime(2006, 10, 17)},
5: new Product {ID = 7, Name = "B", Price = 17, ShipDate = new DateTime(2007, 2, 12)},
6: new Product {ID = 5, Name = "D", Price = 237, ShipDate = new DateTime(2005, 9, 11)}
7: };
(3) 直接進入範例:
1: // 依照 ID 欄位升冪排序、在依 Name 欄位升冪排序
2: foreach (var product in pList.OrderBy(p => p.ID).ThenBy(p => p.Name))
3: {
4: Console.WriteLine(product.ToString());
5: }
6: Console.WriteLine();
7:
8: // 依照 ID 欄位升冪排序、在依 Price 欄位降冪排序、在依 Price 欄位升冪排序
9: foreach (var product in pList.OrderBy(p => p.ID).ThenByDescending(p => p.Price).ThenBy(p => p.ShipDate))
10: {
11: Console.WriteLine(product.ToString());
12: }
13: Console.WriteLine();
(4) 輸出結果:
1: // 依照 ID 欄位升冪排序、在依 Name 欄位升冪排序
2: ID: 1, Name: A, Price: 19, ShipDate: 2006/1/19
3: ID: 5, Name: D, Price: 237, ShipDate: 2005/9/11
4: ID: 7, Name: B, Price: 17, ShipDate: 2007/2/12
5: ID: 7, Name: C, Price: 17, ShipDate: 2006/10/17
6:
7: // 依照 ID 欄位升冪排序、在依 Price 欄位降冪排序、在依 Price 欄位升冪排序
8: ID: 1, Name: A, Price: 19, ShipDate: 2006/1/19
9: ID: 5, Name: D, Price: 237, ShipDate: 2005/9/11
10: ID: 7, Name: C, Price: 17, ShipDate: 2006/10/17
11: ID: 7, Name: B, Price: 17, ShipDate: 2007/2/12