如何使用通用参数构建任何方法的表达式调用 [英] How do I build Expression Call for Any Method with generic parameter
问题描述
我正在尝试使用Linq.Expression进行相同的表达式:
I'm just trying make the same expression like below using Linq.Expression:
Expression<Func<Organization, bool>> expression = @org =>
@org.OrganizationFields.Any(a =>
a.CustomField.Name == field.Name &&
values.Contains(a.Value));
在上面的这个例子中,我有一个名为Organization的实体,它有一个名为OrganizationsFields的属性作为IEnumerable和I想要找到与任何参数表达式匹配的任何事件。
In this example above I have an entity called Organization and it has a property called OrganizationsFields as IEnumerable and I want to find any occurrence that match with Any parameter expression.
我只是使用下面的代码动态生成表达式:
I just using the code below to generate expression dynamically:
string[] values = filter.GetValuesOrDefault();
ParameterExpression parameter = Expression.Parameter(typeof(T), "org");
Expression organizationFields = Expression.Property(parameter, "OrganizationFields");
MethodInfo any = typeof(Enumerable)
.GetMethods()
.FirstOrDefault(a => a.Name == "Any" && a.GetParameters().Count() == 2)
.MakeGenericMethod(typeof(OrganizationField));
Func<OrganizationField, bool> functionExpression = a =>
a.CustomField.Name == filter.Name && values.Contains(a.Value);
Expression functionParam = Expression.Constant(
functionExpression,
typeof(Func<OrganizationField, bool>));
Expression call = Expression.Call(organizationFields, any, functionParam);
return Expression.Lambda<Func<T, bool>>(call, parameter);
当我调用Expression.Call的方法抛出ArgumentExeption
The problems occur when I call the method Expression.Call it throw an ArgumentExeption
任何人都可以帮助我吗?
Can anyone help me?
Regards
推荐答案
这里你去
var org = Expression.Parameter(typeof(Organization), "org");
Expression<Func<OrganizationField, bool>> predicate =
a => a.CustomField.Name == filter.Name && values.Contains(a.Value);
var body = Expression.Call(typeof(Enumerable), "Any", new[] { typeof(OrganizationField) },
Expression.PropertyOrField(org, "OrganizationFields"), predicate);
var lambda = Expression.Lambda<Func<Organization, bool>>(body, org);
主要部分(涵盖您的帖子标题)是以下有用的表达式。致电
overload
$ b
The essential part (covering your post title) is the following useful Expression.Call
overload
public static MethodCallExpression Call(
Type type,
string methodName,
Type[] typeArguments,
params Expression[] arguments
)
另请注意谓词
参数任何
必须传递到 Expression.Call
作为表达式< Func< ...>>
。
Also note that the predicate
argument of Any
must be passed to Expression.Call
as Expression<Func<...>>
.
这篇关于如何使用通用参数构建任何方法的表达式调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!