无法从 'System.Linq.Expressions.LambdaExpression' 转换为"System.Linq.Expressions.Expression



我正在尝试用linq实现表达式树。我得到错误状态,因为无法将lambdaexpression转换为expression。请帮忙,我检查了其他解决方案,但帮不了多少忙!下面是我的代码

ParameterExpression pe = Expression.Parameter(typeof(Person), "p");
var expr = Expression.Lambda(Expression.Property(pe, sortByProp), pe);        
          var d=  expr.Compile();
            IQueryable<Person> query = persons.AsQueryable();
            List<Person> sortedList = query.OrderBy<Person, int>(expr).ToList();

您似乎正在尝试使用表达式树动态实现OrderBy。您应该尝试以下操作:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortProperty, ListSortDirection sortOrder)
{
    var type = typeof(T);
    var property = type.GetProperty(sortProperty);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    var typeArguments = new Type[] { type, property.PropertyType };
    var methodName = sortOrder == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
    var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp));
    return source.Provider.CreateQuery<T>(resultExp);
}

然后你可以称之为:

collection.OrderBy("Property on which you want to sort", ListSortDirection.Ascending);

相关内容

  • 没有找到相关文章

最新更新