2010-01-01 74 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”