Constructing Expression Trees

c# expression-trees lambda linq

Question

I'm having trouble figuring out how to create an expression tree for anything that could contain numerous statements, much alone something with more lambdas like the one below. For instance:

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

Any ideas would be much appreciated.

1
6
6/8/2011 3:12:28 AM

Accepted Answer

I advise reading the a list of the Expression class's methods and the Guide to Programming Expression Trees since they include a complete list of your alternatives.

Regarding this specific 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();
5
6/8/2011 11:39:28 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow