如何创建表达式树来表示C#中的'String.Contains(“term”)'?

时间:2008-11-10 18:11:29

标签: c# .net lambda expression-trees

我刚刚开始使用表达式树,所以我希望这是有道理的。我正在尝试创建一个表达式树来表示:

t => t.SomeProperty.Contains("stringValue");

到目前为止,我有:

    private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue)
    {
        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameter, propertyName);
        var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)
        ...
        return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this
    }

我只是不知道如何引用String.Contains()方法。

帮助表示感谢。

3 个答案:

答案 0 :(得分:125)

类似的东西:

class Foo
{
    public string Bar { get; set; }
}
static void Main()
{
    var lambda = GetExpression<Foo>("Bar", "abc");
    Foo foo = new Foo { Bar = "aabca" };
    bool test = lambda.Compile()(foo);
}
static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
    var parameterExp = Expression.Parameter(typeof(T), "type");
    var propertyExp = Expression.Property(parameterExp, propertyName);
    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var someValue = Expression.Constant(propertyValue, typeof(string));
    var containsMethodExp = Expression.Call(propertyExp, method, someValue);

    return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}

您可能会发现this有帮助。

答案 1 :(得分:7)

这个怎么样:

Expression<Func<string, string, bool>> expFunc = (name, value) => name.Contains(value);

在客户端代码中:

    bool result = expFunc.Compile()("FooBar", "Foo");   //result true
    result = expFunc.Compile()("FooBar", "Boo");        //result false

答案 2 :(得分:0)

以下是如何创建string.Contains的表达式树。

var method = typeof(Enumerable)
    .GetRuntimeMethods()
    .Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2);
var containsMethod = method.MakeGenericMethod(typeof(string));
var doesContain = Expression
.Call(containsMethod, Expression.Constant(criteria.ToArray()),
 Expression.Property(p, "MyParam"));

https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs

的实际使用情况