[ACCEPTED]-Calling a Method from an Expression-lambda

Accepted answer
Score: 11

I had a similar problem when trying to get 12 string.Contains to work; I just used the GetMethod/MethodInfo approach instead; however 11 - it is complicated because it is a generic 10 method...

This should be the right MethodInfo - but 9 it is hard to give a full (runnable) answer 8 without a bit more clarity on Tank and Vehicle:

   MethodInfo method = typeof(Queryable).GetMethods()
        .Where(m => m.Name == "Any"
            && m.GetParameters().Length == 2)
        .Single().MakeGenericMethod(typeof(Tank));

Note 7 that extension methods work backwards - so 6 you actually want to call method with the two 5 args (the source and the predicate).

Something 4 like:

   MethodInfo method = typeof(Queryable).GetMethods()
        .Where(m => m.Name == "Any" && m.GetParameters().Length == 2)
        .Single().MakeGenericMethod(typeof(Tank));

    ParameterExpression vehicleParameter = Expression.Parameter(
        typeof(Vehicle), "v");
    var vehicleFunc = Expression.Lambda<Func<Vehicle, bool>>(
        Expression.Call(
            method,
            Expression.Property(
                vehicleParameter,
                typeof(Vehicle).GetProperty("Tank")),
            tankFunction), vehicleParameter);

If in doubt, use reflector (and fiddle 3 it a bit ;-p) - for example, I wrote a test 2 method as per your spec:

Expression<Func<Vehicle, bool>> func = v => v.Tank.Any(
    t => t.Gun == "Really Big");

And decompiled it 1 and toyed with it...

More Related questions