如何动态排序结果
How to order result dynamically
我正在尝试动态应用排序。我正在使用 EntityFramework
。我正在传递 sortorder
和 sortfield
。现在我不想写条件来按 sortfield
列排序结果。我试过的如下,
public static IOrderedQueryable<TSource> OrderByProperty<TSource, TKey>(this IQueryable<TSource> source, string property, string sortorder)
{
ParameterExpression param = Expression.Parameter(typeof(TSource), "t");
MemberExpression member = Expression.Property(param, property);
var ex = Expression.Lambda<Func<TSource, TKey>>(member, param);
return source.OrderBy<TSource, TKey>(ex);
}
我这样称呼它,
OrderByProperty<Class, dynamic>(objClass, sortfield, sortorder);
当 sortfield
的类型为 System.Int32
时,我遇到以下错误;
Expression of type 'System.Int32' cannot be used for return type 'System.Object'
string
相同。感谢您的帮助。
试试这个扩展方法:
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
我正在尝试动态应用排序。我正在使用 EntityFramework
。我正在传递 sortorder
和 sortfield
。现在我不想写条件来按 sortfield
列排序结果。我试过的如下,
public static IOrderedQueryable<TSource> OrderByProperty<TSource, TKey>(this IQueryable<TSource> source, string property, string sortorder)
{
ParameterExpression param = Expression.Parameter(typeof(TSource), "t");
MemberExpression member = Expression.Property(param, property);
var ex = Expression.Lambda<Func<TSource, TKey>>(member, param);
return source.OrderBy<TSource, TKey>(ex);
}
我这样称呼它,
OrderByProperty<Class, dynamic>(objClass, sortfield, sortorder);
当 sortfield
的类型为 System.Int32
时,我遇到以下错误;
Expression of type 'System.Int32' cannot be used for return type 'System.Object'
string
相同。感谢您的帮助。
试试这个扩展方法:
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}