如何在linq中使用orderby和2个字段?

时间:2010-01-01 21:20:31

标签: c# linq

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

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更重要的是先行。我不确定是否需要更改它以使用某些比较功能或其他东西。

5 个答案:

答案 0 :(得分:190)

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

答案 1 :(得分:52)

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

答案 2 :(得分:7)

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

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

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

答案 3 :(得分:5)

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

答案 4 :(得分:3)

如果您有两个或更多要求的字段,请尝试以下操作:

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

您可以使用clasole" ThenBy"

添加其他字段
相关问题