如何使用通用参数为任何方法构建表达式调用

时间:2016-01-11 20:25:43

标签: c# linq reflection expression

我只是尝试使用Linq.Expression创建与下面相同的表达式:

Expression<Func<Organization, bool>> expression = @org => 
    @org.OrganizationFields.Any(a =>
        a.CustomField.Name == field.Name &&
        values.Contains(a.Value));

在上面的这个例子中,我有一个名为Organization的实体,它有一个名为OrganizationsFields的属性为IEnumerable,我想查找与Any参数表达式匹配的任何匹配项。

我只是使用下面的代码动态生成表达式:

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

时会出现问题

任何人都可以帮助我吗?

此致

1 个答案:

答案 0 :(得分:6)

你去吧

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

基本部分(包括您的帖子标题)是以下有用Expression.Call overload

public static MethodCallExpression Call(
    Type type,
    string methodName,
    Type[] typeArguments,
    params Expression[] arguments
)

另请注意,predicate的{​​{1}}参数必须作为Any传递给Expression.Call