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

cho*_*bo2 129 c# linq

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

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

id = 2
StartDate = 1/3/2010
EndDate = 1/9/2010
Run Code Online (Sandbox Code Playgroud)

现在我已经为我的linq订购了这个订单

var hold = MyList.OrderBy(x => x.StartDate).ToList();
Run Code Online (Sandbox Code Playgroud)

我想订购它,但也使用结束日期.

就像我要这样的顺序一样

id 2
id 1
Run Code Online (Sandbox Code Playgroud)

所以endDates这是更好的先行.我不确定是否需要更改它以使用某些比较功能或其他东西.

mqp*_*mqp 216

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Run Code Online (Sandbox Code Playgroud)


jas*_*son 56

用途ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();
Run Code Online (Sandbox Code Playgroud)

您还可以使用查询语法并说:

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();
Run Code Online (Sandbox Code Playgroud)

ThenByDescending是一个扩展方法,IOrderedEnumerable返回的是OrderBy.另请参见相关方法ThenBy.


dan*_*004 9

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

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);
Run Code Online (Sandbox Code Playgroud)

您可以使用 clasole "ThenBy" 添加其他字段


小智 7

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Run Code Online (Sandbox Code Playgroud)

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

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);
Run Code Online (Sandbox Code Playgroud)


Abd*_*oor 5

VB.NET

 MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)
Run Code Online (Sandbox Code Playgroud)

要么

  From l In MyList Order By l.StartDate Ascending, l.EndDate Descending
Run Code Online (Sandbox Code Playgroud)

  • `是从l在MyList中按顺序l.StartDate升序通过l.EndDate Descending`和`from l in MyList Order by l.StartDate Ascending,l.EndDate Descending`? (2认同)