[英]LiNQ using ThenBy after OrderBy
I have a collection and number of OrderBy statemensts which sorts using query.Sort parameter 我有一个OrderBy州议员的集合和数量,使用query.Sort参数进行排序
switch (filters.Sort)
{
case "new":
query = query.OrderByDescending(a => a.CreatedAt);
break;
case "old":
query = query.OrderBy(a => a.CreatedAt);
break;
case "salary-asc":
query = query.OrderBy(a => a.Profile.CompensationTypeRate.FromCompensation);
}
Now I need to apply another sort using a query.Grade
parameter. 现在我需要使用
query.Grade
参数应用另一种排序。 I know I should be using ThenBy
to have multiple Order statements, but in this case I cannot write it in one line. 我知道我应该使用
ThenBy
来拥有多个Order语句,但在这种情况下我不能将它写在一行中。
Is there a way to write OrderBy
and ThenBy
so they are executed one by one, and not in one line? 是否有办法编写
OrderBy
和ThenBy
以便逐个执行,而不是一行?
Or can I create some anonymous function that contains my OrderBy
and ThenBy
conditions ? 或者我可以创建一个包含我的
OrderBy
和ThenBy
条件的匿名函数吗?
You can do it in two parts if you use a variable of type IOrderedQueryable<T>
- that's what enables ThenBy
. 如果使用
IOrderedQueryable<T>
类型的变量,则可以IOrderedQueryable<T>
- 这就是启用ThenBy
。 For example: 例如:
IOrderedQueryable<Application> ordered;
switch (filters.Sort)
{
case "new":
ordered = query.OrderByDescending(a => a.CreatedAt);
break;
case "old":
ordered = query.OrderBy(a => a.CreatedAt);
break;
case "salary-asc":
ordered = query.OrderBy(a => a.Profile.CompensationTypeRate.FromCompensation);
default:
// You need to work out what you want to do here. Maybe just
// order by ID? You need to order by *something* to start with
// in order to use ThenBy
}
// Apply the same secondary ordering, regardless of the primary one
ordered = ordered.ThenBy(x => x.Grade);
// You can then continue to use ordered, or assign the value back
// to query:
query = ordered;
Note that all of this will still be lazy. 请注意,所有这些仍然是懒惰的。 The ordering won't actually happen until you try to use the results.
在您尝试使用结果之前,实际上不会发生排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.