Combining two lambda expressions in c#

Viewed 14907

Given a class structure like this:

public class GrandParent
{
    public Parent Parent { get; set;}
}
public class Parent
{
    public Child Child { get; set;}
}

public class Child
{
    public string Name { get; set;}
}

and the following method signature:

Expression<Func<TOuter, TInner>> Combine (Expression<Func<TOuter, TMiddle>>> first, Expression<Func<TMiddle, TInner>> second);

How can I implement said method so that I can call it like this:

Expression<Func<GrandParent, Parent>>> myFirst = gp => gp.Parent;
Expression<Func<Parent, string>> mySecond = p => p.Child.Name;

Expression<Func<GrandParent, string>> output = Combine(myFirst, mySecond);

such that output ends up as:

gp => gp.Parent.Child.Name

Is this possible?

The contents of each Func will only ever be a MemberAccess. I'd rather not end up with output being a nested function call.

Thanks

8 Answers

After a half-day's digging came up with the following solution (much simpler than the accepted answer):

For generic lambda composition:

    public static Expression<Func<X, Z>> Compose<X, Y, Z>(Expression<Func<Y, Z>> f, Expression<Func<X, Y>> g)
    {
        return Expression.Lambda<Func<X, Z>>(Expression.Invoke(f, Expression.Invoke(g, g.Parameters[0])), g.Parameters);
    }

This combines two expressions in one, i.e. applies the first expression to the result of the second.

So if we have f(y) and g(x), combine(f,g)(x) === f(g(x))

Transitive and associative, so the combinator can be chained

More specifically, for property access (needed for MVC/EF):

    public static Expression<Func<X, Z>> Property<X, Y, Z>(Expression<Func<X, Y>> fObj, Expression<Func<Y, Z>> fProp)
    {
        return Expression.Lambda<Func<X, Z>>(Expression.Property(fObj.Body, (fProp.Body as MemberExpression).Member as PropertyInfo), fObj.Parameters);
    }

Note: fProp must be a simple property access expression, such as x => x.Prop.

fObj can be any expression (but must be MVC-compatible)

Related