2010-01-01 76 views
79

說我在一個數據庫表如何在linq中使用orderby和2個字段?

id = 1 
StartDate = 1/3/2010 
EndDate = 1/3/2010 

id = 2 
StartDate = 1/3/2010 
EndDate = 1/9/2010 

有這些價值觀現在我到目前爲止這個排序依據我的LINQ

var hold = MyList.OrderBy(x => x.StartDate).ToList(); 

我想訂購但是也可以使用結束日期。

像這樣的順序我就在想這是

id 2 
id 1 

所以endDates是更大的先走。我不確定是否需要改變這個來使用一些比較函數或其他東西。

+4

的可能重複[多「在LINQ中排序」(http://stackoverflow.com/questions/298725/multiple-order-by-in-linq) – Moes 2015-05-12 06:46:02

回答

135
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate); 
38

使用ThenByDescending

var hold = MyList.OrderBy(x => x.StartDate) 
       .ThenByDescending(x => x.EndDate) 
       .ToList(); 

您還可以使用查詢語法和說:

var hold = (from x in MyList 
      orderby x.StartDate, x.EndDate descending 
      select x).ToList(); 

ThenByDescendingIOrderedEnumerable擴展方法是什麼是OrderBy返回。另見相關方法ThenBy

+0

謝謝 - 你還會知道結構的類型是什麼? MyList項目列表? – BKSpurgeon 2017-02-07 05:06:36

3

VB.NET

MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate) 

OR

From l In MyList Order By l.StartDate Ascending, l.EndDate Descending 
+2

'從l在MyList順序通過l.StartDate升序順序由l.EndDate降序'和'從l在MyList順序通過l.StartDate升序,l.EndDate降序'有任何區別? – Oleksandr 2014-10-07 12:10:07

+0

@ Oleksandr是的,Abdul的變體相當於僅僅執行二階,所以它是不正確的。 – John 2014-11-05 13:52:36

+0

@John和@oleksandr感謝您識別錯誤並未糾正 – 2015-03-09 16:08:21

4
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate); 

注意,您可以在排序依據使用,以及在降序關鍵字(如果你需要)。因此,另一種可能的答案是:

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate); 
1

如果有兩個或兩個以上領域的訂購試試這個:

var soterdList = initialList.OrderBy(x => x.Priority). 
            ThenBy(x => x.ArrivalDate). 
            ThenBy(x => x.ShipDate); 

您可以clasole添加其他字段「ThenBy」