I am looking for a way to combine two lambda expressions, without using an Expression.Invoke on either expression. I want to essentially build a new expression
Use a visitor to swap all instances of the parameter f to m.SubModel.Foo, and create a new expression with m as the parameter:
internal static class Program
{
static void Main()
{
Expression> expression1 = m => m.SubModel.Foo;
Expression> expression2 = f => f.Bar.Value;
var swap = new SwapVisitor(expression2.Parameters[0], expression1.Body);
var lambda = Expression.Lambda>(
swap.Visit(expression2.Body), expression1.Parameters);
// test it worked
var func = lambda.Compile();
Model test = new Model {SubModel = new SubModel {Foo = new Foo {
Bar = new Bar { Value = "abc"}}}};
Console.WriteLine(func(test)); // "abc"
}
}
class SwapVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public SwapVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}