How do I create an expression tree to represent 'String.Contains("term")' in C#?

flesh picture flesh · Nov 10, 2008 · Viewed 37k times · Source

I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:

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

So far I have got:

    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
    }

I just don't know how to reference the String.Contains() method.

Help appreciated.

Answer

Marc Gravell picture Marc Gravell · Nov 10, 2008

Something like:

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

You might find this helpful.