C# Linq-如何按三个表达式动态排序?
我想通过动态C# Linq-如何按三个表达式动态排序?,c#,linq,C#,Linq,我想通过动态表达式变量对结果进行排序。如果我将DateTime、double?和int更改为对象,我会得到一个NotSupportedException。我有以下三个表达 Expression<Func<Recipe, DateTime>> byCreatedOn = x => x.CreatedOn; Expression<Func<Recipe, double?>> byRank = entity => entity.Comment
表达式
变量对结果进行排序。如果我将DateTime
、double?
和int
更改为对象
,我会得到一个NotSupportedException
。我有以下三个表达
Expression<Func<Recipe, DateTime>> byCreatedOn = x => x.CreatedOn;
Expression<Func<Recipe, double?>> byRank = entity => entity.Comments.Any() ? entity.Comments.Average(comment => comment.Rating) : 0;
Expression<Func<Recipe, int>> byPopularity = x => x.Comments.Count();
var expression = order == 1 ? byRank : (order == 2 ? byPopularity : byCreatedOn);
只要表达式进行计算,您就应该能够执行以下操作:
.OrderByDescending(expression1).ThenBy(expression2)
依此类推。只要表达式进行计算,您就应该能够执行以下操作:
.OrderByDescending(expression1).ThenBy(expression2)
等等。要做的一件事是将查询构建从物化中分离出来
var query = this.DbContext.RecipeTranslations
.Where(x => x.Language.Code == this.CurrentLanguge)
.Where(x => string.IsNullOrEmpty(name) || x.Title.Contains(name))
.Select(x => x.Recipe)
.Where(x => x.IsDeleted == false)
.Where(x => category == null || x.Categories.Any(cat => cat.Id == category));
if (order == 1)
{
query = query.OrderByDescending(byRank);
}
else if (order == 2)
{
query = query.OrderByDescending(byPopularity);
}
else
{
query = query.OrderByDescending(byCreatedOn);
}
// Finally
var list = query.Skip(start).Take(size).toList();
要做的一件事是从物化中分离出查询构建
var query = this.DbContext.RecipeTranslations
.Where(x => x.Language.Code == this.CurrentLanguge)
.Where(x => string.IsNullOrEmpty(name) || x.Title.Contains(name))
.Select(x => x.Recipe)
.Where(x => x.IsDeleted == false)
.Where(x => category == null || x.Categories.Any(cat => cat.Id == category));
if (order == 1)
{
query = query.OrderByDescending(byRank);
}
else if (order == 2)
{
query = query.OrderByDescending(byPopularity);
}
else
{
query = query.OrderByDescending(byCreatedOn);
}
// Finally
var list = query.Skip(start).Take(size).toList();
int
,double
,DateTime
已经实现了IComparable
接口
对象类型(您使用的对象而不是int
、DateTime
或double
)也应该实现IComparable
接口
或者您可以尝试其他重载的
OrderByDescending
方法,该方法要求使用比较器。int
,double
,DateTime
已经实现了IComparable
接口
对象类型(您使用的对象而不是int
、DateTime
或double
)也应该实现IComparable
接口
或者您可以尝试其他重载的
OrderByDescending
方法,它需要一个比较器。我希望只根据变量顺序按一个表达式排序,而不使用ThenBy
,也不在开关或if中写入3个不同的查询。我希望只根据变量顺序按一个表达式排序,而不使用ThenBy
,也不在一个表达式中写入3个不同的查询切换或如果。