gpt4 book ai didi

c# - Linq thenBy() 抛出 "The best overloaded method match ThenBy() for has some invalid arguments"异常

转载 作者:行者123 更新时间:2023-11-30 20:39:56 29 4
gpt4 key购买 nike

我有以下方法:

public List<LambdaExpression> defaultSortExpressions { get; set; }

private IQueryable<TEntity> orderEntries(IQueryable<TEntity> entries)
{
var n = 0;
foreach (var sortExpression in defaultSortExpressions)
{
if (n == 0)
{
entries = Queryable.OrderBy(entries, (dynamic)sortExpression);
}
else
{
entries = Queryable.ThenBy(entries, (dynamic)sortExpression);
}
n = n + 1;
}
return entries;
}

当执行 TheyBy() 行时,我收到以下异常:

"The best overloaded method match for 'System.Linq.Queryable.ThenBy(System.Linq.IOrderedQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments"}
System.Exception {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

为什么这不起作用?

最佳答案

entries在编译时被强强制转换为 IQueryable<TEntity> ,而ThenBy需要 IOrderedQueryable<TEntity> 。您可以尝试类型转换 entriesIOrderedQueryable<TEntity>在将其传递给 ThenBy() 之前。或者您可以捕获调用 OrderBy 的结果在具有正确类型的单独变量中调用 ThenBy上。

private IQueryable<TEntity> orderEntries(IQueryable<TEntity> entries)
{
if(defaultSortExpressions.Count == 0)
return entries;
IOrderedQueryable<TEntity> ordered = Queryable.OrderBy(entries, (dynamic) defaultSortExpressions[0]);

foreach (var sortExpression in defaultSortExpressions.Skip(1))
{
ordered = Queryable.ThenBy(ordered, (dynamic)sortExpression);
}
return ordered;
}

关于c# - Linq thenBy() 抛出 "The best overloaded method match ThenBy() for has some invalid arguments"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901328/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com