Q: Selecting from Lambda Expression with Lambda Expression I have two expressions:
  public static Expression<Func<TSource, TReturn>> Merge<TSource, TSource2, TReturn>(
      Expression<Func<TSource, TSource2>> foo1
      Expression<Func<TSource2, TReturn>> foo2)
  {
      // What to do?
  }

How can I merge them into a single expression, so the output from the first is used as the input for the second? I am new to these and so far its just been exceptions.
Thanks

A: This depends a lot on which providers need to use it. Some will be fine with:
public static Expression<Func<TSource, TReturn>>
     Merge<TSource, TSource2, TReturn>(
  Expression<Func<TSource, TSource2>> foo1,
  Expression<Func<TSource2, TReturn>> foo2)
{
    return Expression.Lambda<Func<TSource, TReturn>>(
      Expression.Invoke(foo2, foo1.Body),
      foo1.Parameters);
}

However, others (EF) will not. You can also re-write the expression-tree with a visitor to inline the expression:
public static Expression<Func<TSource, TReturn>>
      Merge<TSource, TSource2, TReturn>(
  Expression<Func<TSource, TSource2>> foo1,
  Expression<Func<TSource2, TReturn>> foo2)
{
    var swapped = new SwapVisitor(
        foo2.Parameters.Single(), foo1.Body).Visit(foo2.Body);
    return Expression.Lambda<Func<TSource, TReturn>>(
        swapped, foo1.Parameters);
}

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

this will work with all providers.
