扩展IQueryable的位置 [英] extend Where for IQueryable
问题描述
我需要将 Where
方法扩展为 IQueryable
,如下所示:
I need to extend the Where
method for IQueryable
to something like this:
.WhereEx(SomeProperty,==,value)
我不知道这是否可能,但是我在这里发现了这一点:无法使用LINQ OrderBy中的属性名称排序
I dont know if this is even possible, but i found this in SO : Unable to sort with property name in LINQ OrderBy
我尝试了这个答案,这似乎很有趣(Ziad的回答):
I tried this answer and it seems quite interesting (Ziad's answer):
using System.Linq;
using System.Linq.Expressions;
using System;
namespace SomeNameSpace
{
public static class SomeExtensionClass
{
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);
}
}
}
是否可以与 Where
方法相同?
谢谢。
更新:
我现在可以设置一个表达式传递给调用
方法,但是我得到以下异常:无通用方法其中'在类型System.Linq.Queryable与提供的类型参数和参数兼容。如果方法非泛型,则不应提供类型参数。
I can now set an expression to pass to the Call
method, but i get the following exception: "No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic."
这是我的代码:
public static IQueryable<T> WhereEx<T>(this IQueryable<T> q, string Field, string Operator, string Value)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, Field);
var val = Expression.Constant(Value);
var body = Expression.Equal(prop, val);
var exp = Expression.Lambda<Func<T, bool>>(body, param);
Type[] types = new Type[] { q.ElementType, typeof(bool) };
var mce = Expression.Call(
typeof(Queryable),
"Where",
types,
exp
);
return q.Provider.CreateQuery<T>(mce);
}
请注意,我不使用运算符
参数,而是使用 Equal
进行调试。
Notice that i dont use the Operator
argument yet, instead i use Equal
for debugging purpose.
有人可以帮我吗?
推荐答案
我做了一个简单问题的另一篇文章。该链接是此处
I did another post with a simplified question. the link is Here
public static IQueryable<T> WhereEx<T>(this IQueryable<T> q, string Field, string Operator, string Value)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, Field);
var val = Expression.Constant(Value);
var body = Expression.Equal(prop, val);
var exp = Expression.Lambda<Func<T, bool>>(body, param);
return System.Linq.Queryable.Where(q, exp);
}
这篇关于扩展IQueryable的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!