表达式谓词具有多个参数



我在这里使用Marc Gravell在Stackoverflow上给出的代码:http://goo.gl/57nW2

代码 :

var param = Expression.Parameter(typeof (Foo));
var pred = Expression.Lambda<Func<Foo, bool>>(
    Expression.Call(
        Expression.PropertyOrField(param, fieldName),
        "StartsWith",null,
        Expression.Constant(stringToSearch)), param);

现在,我想结合几个参数,示例:

    public void BuildPredicate(string[] typeSearch, string[] field, string searchValue)
    {
       //Content
       //typeSearch = new string[] {"Contains", "StartsWith", "StartsWith" };
       //field = new string[] { "FieldA", "FieldB", "FieldC" };
      //FieldA contains searchValue and FieldB startWith searchValue and FieldC startWith searchValue
    }

一个想法 ?

谢谢

您可以简单地遍历所有字段上的所有操作,并为每个类型/字段组合构建一个包含 OrElse 子句的表达式树

var expressions = from type in typeSearch
                  from field in fields
                  select Expression.Call(
                    Expression.PropertyOrField(param, field),
                    type, null,
                    Expression.Constant(stringToSearch));
Expression body = Expression.Constant(false);
foreach (Expression expression in expressions)
{
    body = Expression.OrElse(body, expression);
}
var result = Expression.Lambda<Func<Foo, bool>>(body, param);

根据要求,一个包括对ToUpper调用的示例:

var expressions = from type in typeSearch
                  from field in fields
                  select Expression.Call(
                    Expression.Call(
                        Expression.PropertyOrField(param, field),
                        "ToUpper", null),
                    type, null,
                    Expression.Constant(stringToSearch));

最新更新