如何在 linq 中使用带有2个字段的 orderby?

假设我在数据库表中有这些值

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先走。我不确定是否需要改变这一点,以使用一些比较函数或东西。

203833 次浏览
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

使用 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返回的方法。

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
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

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

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

如果您有两个或多个字段可以排序,请尝试这样做:

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

您可以使用类库“ ThenBy”添加其他字段