如何在Linq中使用两个字段进行排序?

191

假设我在数据库表中有以下数值:

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

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

现在我已经有了这个linq的orderby

var hold = MyList.OrderBy(x => x.StartDate).ToList();
我想按照结束日期来排序它。
就像这样,我想要的排序方式是:
id 2
id 1

所以先排列那些更大的endDates。我不确定是否需要改变这个过程使用某种比较函数或其他方法。

5个回答

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

81

使用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


谢谢 - 你也知道hold的结构类型吗?是MyList项目的列表吗? - BenKoshy

24

如果您有两个或更多字段需要排序,请尝试以下方法:

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

您可以使用“ThenBy”子句添加其他字段。


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

请注意,您也可以在OrderBy中使用Descending关键字(如果需要的话)。因此,另一个可能的答案是:

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

6

VB.NET

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

或者

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

2
“From l In MyList Order By l.StartDate Ascending Order By l.EndDate Descending” 和 “From l In MyList Order By l.StartDate Ascending, l.EndDate Descending” 之间有什么区别吗? - Oleksandr
@Oleksandr 是的,Abdul的变体相当于仅执行第二个顺序,因此不正确。 - John
@John 和 @oleksandr,感谢你们指出错误,现在已经被纠正了。 - Abdul Saboor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接