怎样申请的OrderBy在一个IQueryable中的一个通用的扩展方法使用一个字符串列名? [英] How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?

查看:511
本文介绍了怎样申请的OrderBy在一个IQueryable中的一个通用的扩展方法使用一个字符串列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName)
  where T : EntityObject
{
  var param = Expression.Parameter(typeof(T), "o");
  var body = Expression.PropertyOrField(param,columnName);

  var sortExpression = Expression.Lambda(body, param);
  return query.OrderBy(sortExpression);
}

由于为排序依据的类型不是从SORTEX pression推断我需要指定它是这样的,在运行时:

Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:

var sortExpression = Expression.Lambda<T, TSortColumn>(body, param);

return query.OrderBy<T, TSortColumn>(sortExpression);

我不认为这是可能的但作为TSortColumn只能在运行时确定。

I don't think this is possible however as TSortColumn can only be determined during runtime.

有没有解决的办法吗?

推荐答案

我们没有类似的东西(不是100%相同,但大同小异)在LINQ to SQL中的项目。这里的code:

We did something similar (not 100% the same, but similar) in a LINQ to SQL project. Here's the code:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) {
    var type = typeof(T);
    var property = type.GetProperty(ordering);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
    return source.Provider.CreateQuery<T>(resultExp);
}

我们实际上并没有使用一个通用的,我们有一个已知的类,但它应该在一个通用的(我已经把通用占位符,它应该是)。

We didn't actually use a generic, we had a known class, but it should work on a generic (I've put the generic placeholder where it should be).

编辑:对于降序排列,传递 OrderByDescending 而不是排序依据:

For descending order, pass in OrderByDescending instead of "OrderBy":

MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));

这篇关于怎样申请的OrderBy在一个IQueryable中的一个通用的扩展方法使用一个字符串列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆