How do I create an expression tree for run time sorting?

后端 未结 2 1612
囚心锁ツ
囚心锁ツ 2020-12-01 08:29

Using Entity Framework 4, I\'m trying to implement dynamic sorting based on a collection of member names. Basically, the user can select fields to sort and the order of the

2条回答
  •  温柔的废话
    2020-12-01 09:11

    Is exactly what I needed Kevin. What I noticed is that if you use the orderby it only takes the last orderby selection.

    I added this method (ThenBy) to mine and it seems to work well

    public static IQueryable ThenBy(this IQueryable source, string sortProperty, ListSortDirection sortOrder)
        {
            var type = typeof(T);
            var property = type.GetTypeInfo().GetDeclaredProperty(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 ? "ThenBy" : "ThenByDescending";
            var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp));
    
            return source.Provider.CreateQuery(resultExp);
        }
    

提交回复
热议问题