如何使用通用扩展方法中的字符串列名在 IQueryable 上应用 OrderBy? [英] How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?

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

问题描述

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

因为 OrderBy 的类型不是从 sortExpression 推断出来的,所以我需要在运行时指定类似这样的内容:

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.

有没有办法解决这个问题?

Is there a way around this?

推荐答案

我们在一个 LINQ to SQL 项目中做了类似的事情(不是 100% 相同,而是类似).代码如下:

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 而不是OrderBy":

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

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

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