Cannot convert from 'System.Linq.Expressions.LambdaExpression' to 'System.Linq.Expressions.Expression

c# expression-trees linq

Question

I'm trying to implement expression tree with linq.I am getting error state as cannot convert lambdaexpression to expression. Please help i checked other solution but couldn't help as much ! Below is my code

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();

Accepted Answer

It seems like you are trying to implement OrderBy dynamically using expression trees. You should try the following:

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);
}

and then you can call it as:

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


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why