views:

982

answers:

2

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.

+8  A: 

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.

Marc Gravell
Brilliant, thanks! Nice blog too.
flesh
Damn Marc. You are a coding beast.
Nicholas Mancuso
Awesome, thanks Marc! I was using the "string methodName" version of Expression.Call and it wasn't having any of it. Tried it by getting the MethodInfo myself and now it's rocking!
tags2k
A: 

How about this:

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

In the client code:

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