我有一个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);
}
现在我需要使用query.Grade
参数应用另一种排序。我知道我应该使用ThenBy
来生成多个Order语句,但在这种情况下我不能将它写在一行中。
有没有办法写OrderBy
和ThenBy
所以它们是一个一个地执行,而不是一行执行?
或者我可以创建一个包含OrderBy
和ThenBy
条件的匿名函数吗?
答案 0 :(得分:3)
如果您使用IOrderedQueryable<T>
类型的变量,那么您可以分两部分进行 - 这是启用ThenBy
的内容。例如:
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;
请注意,所有这些仍然是懒惰的。在尝试使用结果之前,订单实际上发生。