Lets say i have :
Func<Customer,bool > a = (c) => c.fullName == "John";
now i want to convert to expressiontree any way to do that ?
i know i can define it from the first place as expressiontree but the situation i have is different because i must concatenate some lambda expressions first then pass it to a method which take expressiontree, doing so result in compile time error!
example:
Func<Customer, bool> a = (c) => c.fullName == "John";
Func<Customer, bool> b = (c) => c.LastName == "Smith";
Func<Customer, bool> final = c => a(c) && b(c);
now i want to pass final to a method which takes
ExpressionTree<Func<Customer,bool >>
it gives compile time error
thanks in advance
You cannot do that. A variable of type Func<...> is a delegate, which is basically like a pointer to a memory location that contains the compiled code for the lambda expression. There is no functionality in .NET to turn already-compiled code back into an expression tree.
Depending on what you are trying to do, maybe you can contend with an incomplete solution: create an expression tree that calls the delegates. Since I don’t know anything about the method to which you want to pass the expression tree, I have no idea whether this is at all a feasible solution for you.
Summary: If you want the complete expression tree of all the expressions, you need to make sure that they are expression trees right from the start. As soon as you compile it into a delegate, the expression tree is lost.
Once you’ve made sure that they are expression trees, you can combine them using something like the following:
Expression<Func<Customer, bool>> a = c => c.FullName == "John";
Expression<Func<Customer, bool>> b = c => c.LastName == "Smith";
var cp = Expression.Parameter(typeof(Customer), "c");
var ai = Expression.Invoke(a, cp);
var bi = Expression.Invoke(b, cp);
var final = Expression.Lambda<Func<Customer, bool>>(
Expression.AndAlso(ai, bi), cp);
Of course, this uses the AndAlso operator (&&); you can also use OrElse for || etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With