How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?(如何使用通用扩展方法中的字符串列名在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用通用扩展方法中的字符串列名在 IQueryable 上应用 OrderBy?


基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01