Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building Expression Trees

I'm struggling with the idea of how to build an expression tree for more lambdas such as the one below, let alone something that might have multiple statements. For example:

Func<double?, byte[]> GetBytes
      = x => x.HasValue ? BitConverter.GetBytes(x.Value) : new byte[1] { 0xFF };

I would appreciate any thoughts.

like image 230
Craig D Avatar asked Jun 08 '11 03:06

Craig D


People also ask

How is an expression tree constructed?

The construction of the expression tree takes place by reading the postfix expression one symbol at a time. If the symbol is an operand, a new binary tree node is created, and its pointer is pushed onto a stack.

What do you mean by expression tree?

Construction of Expression Tree: We loop through input expression and do the following for every character. If a character is an operand push that into the stack. If a character is an operator pop two values from the stack make them its child and push the current node again.


1 Answers

I would suggest reading through the list of methods on the Expression class, all of your options are listed there, and the Expression Trees Programming Guide.

As for this particular instance:

/* build our parameters */
var pX = Expression.Parameter(typeof(double?));

/* build the body */
var body = Expression.Condition(
    /* condition */
    Expression.Property(pX, "HasValue"),
    /* if-true */
    Expression.Call(typeof(BitConverter),
                    "GetBytes",
                    null, /* no generic type arguments */
                    Expression.Member(pX, "Value")),
    /* if-false */
    Expression.Constant(new byte[] { 0xFF })
);

/* build the method */
var lambda = Expression.Lambda<Func<double?,byte[]>>(body, pX);

Func<double?,byte[]> compiled = lambda.Compile();
like image 100
user7116 Avatar answered Oct 11 '22 21:10

user7116