views:

45

answers:

1

I want a Linq Expression which dynamically compiles at runtime

I have a value and if than value greater than say for e.g. 5000 and another value > 70 then it should return a constant x else value greater than say 5000 and another value < 70 it returns y How do I create an expression tree a > 5000 & b < 70 then d else a > 5000 & b >70 then e

+2  A: 

You can use a lambda expression with the ternary operator (?:).

var d = 1;
var e = 2;
var f = 3;

Expression<Func<int,int,int>> expression =
    (a, b) => (a > 5000 && b < 70) ? d :
              (a > 5000 && b > 70) ? e :
              f; // If b == 70

var func = expression.Compile();
var val = func(5432, 1);
dahlbyk
chugh97
How do you mean? The whole lambda will be converted into an expression tree at compile time - open in Reflector to see exactly what it produced.
dahlbyk