title: BinaryExpression to Lambda
body: <p>This may be familiar to some. I have a wrapper class <code>Ex</code> that wraps an expression tree with a bunch of implicit conversions and operators. Here is simplified version</p>
  
  <pre><code>public class Ex 
  {
      Expression expr;
  
      public Ex(Expression expr)
      {
          this.expr = expr;
      }
      public static implicit operator Expression(Ex rhs) { return rhs.expr; }
      public static implicit operator Ex(double value) 
      { return new Ex(Expression.Constant(value, typeof(double))); }
      public static implicit operator Ex(string x) 
      { return new Ex(Expression.Parameter(typeof(double), x)); }
      public static Ex operator +(Ex left, Ex right)
      {
          return new Ex(Expression.Add(left, right));
      }
      public static Ex operator -(Ex rhs)
      {
          return new Ex(Expression.Negate(rhs));
      }
      public static Ex operator -(Ex left, Ex right)
      {
          return new Ex(Expression.Subtract(left, right));
      }
      public static Ex operator *(Ex left, Ex right)
      {
          return new Ex(Expression.Multiply(left, right));
      }
      public static Ex operator /(Ex left, Ex right)
      {
          return new Ex(Expression.Divide(left, right));
      }
  }
  </code></pre>
  
  <p>So here is what I want to do:</p>
  
  <pre><code>{ ...
      Ex x = "x";
      Ex y = 10.0;
      Ex z = x + y;
  
      LambdaExpression lambda = BuildLambda(z);
      Func&lt;double,double&gt; f = (Func&lt;double,double&gt;)lambda.Compile();
  
      // f(5) = 15
  
  }
  </code></pre>
  
  <p>But how to I transverse the tree propely and build my lambda's (or delegates)</p>
  
  <pre><code>    LambdaExpression BuildLambda(Expression e)
      {
          ConstantExpression cex = e as ConstantExpression;
          if(cex != null)
          {
              return Expression.Lambda&lt;Func&lt;double&gt;&gt;( cex );
          }
          ParameterExpression pex = e as ParameterExpression;
          if (pex != null)
          {
              Func&lt;Expression, Expression&gt; f = (x) =&gt; x;
              Expression body = f(pex);
              return Expression.Lambda&lt;Func&lt;double, double&gt;&gt;( body , pex);
          }
          BinaryExpression bex = e as BinaryExpression;
          if (bex != null)
          {
              LambdaExpression left = GetLambda(bex.Left);
              LambdaExpression rght = GetLambda(bex.Right);
     // Now what?
          }
          return null;
      }
  </code></pre>
  
  <p>I have tried several things to get to convert the <code>BinaryExpression</code> bex into a lambda, and all have been unsucessful up to now. I'd like some suggestions and pointers. Note that the operands of the operation might be other expression objects and only at the leafs of the tree they will either be <code>ParameterExpression</code> or <code>ConstantExpression</code>.</p>
  
  <p>Thanks.</p>