0

我在这里使用 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
    }

一个主意 ?

谢谢,

4

1 回答 1

2

您可以简单地遍历所有字段上的所有操作,并为每个类型/字段组合构建一个包含 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));
于 2012-07-05T05:44:42.693 回答