C# 如何在 linq 中使用带有 2 个字段的 orderby?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1989674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use orderby with 2 fields in linq?
提问by chobo2
Say I have these values in a database table
假设我在数据库表中有这些值
id = 1
StartDate = 1/3/2010
EndDate = 1/3/2010
id = 2
StartDate = 1/3/2010
EndDate = 1/9/2010
Now I have so far this orderby for my linq
现在我的 linq 已经有了这个 orderby
var hold = MyList.OrderBy(x => x.StartDate).ToList();
I want to order it however also using the end date.
我想订购它但是也使用结束日期。
Like so the order I would want this in as
就像我想要的顺序一样
id 2
id 1
So endDatesthat are greater go first. I am not sure if I need to change this to use some compare function or something.
所以endDates更大的先走。我不确定是否需要更改它以使用一些比较功能或其他功能。
采纳答案by mqp
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
回答by jason
Use ThenByDescending:
var hold = MyList.OrderBy(x => x.StartDate)
.ThenByDescending(x => x.EndDate)
.ToList();
You can also use query syntax and say:
您还可以使用查询语法并说:
var hold = (from x in MyList
orderby x.StartDate, x.EndDate descending
select x).ToList();
ThenByDescendingis an extension method on IOrderedEnumerablewhich is what is returned by OrderBy. See also the related method ThenBy.
ThenByDescending是一个扩展方法IOrderedEnumerable,OrderBy. 另请参阅相关方法ThenBy。
回答by Abdul Saboor
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
回答by Hugo Passos
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:
请注意,您也可以在 OrderBy 中使用 Descending 关键字(如果需要)。所以另一个可能的答案是:
MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);
回答by daniele3004
If you have two or more field to order try this:
如果您要订购两个或更多字段,请尝试以下操作:
var soterdList = initialList.OrderBy(x => x.Priority).
ThenBy(x => x.ArrivalDate).
ThenBy(x => x.ShipDate);
You can add other fields with clasole "ThenBy"
您可以使用 clasole "ThenBy" 添加其他字段

