Deserializing of Expression tree using ExpressionSerialization on a full conditional expression i.e ternary operator is giving error . If i am using ternary operator it causes FullConditionExpression (System Not Supported Exception)
Using code from following links:
http://archive.msdn.microsoft.com/exprserialization
Are there any latest version available for the above link?
http://metalinq.codeplex.com/
Tried this afterwards
public Expression<Func<object, string>> LabelCriteria { get; set; }
LabelCriteria = x =>
{
if (true)
return "Cash";
else
return " ";
}
Expression doesn't support if - else block . It gives error as " A lambda expression with a statement body cannot be converted to expression tree . Is there any other way to do it.
Each node in an expression tree is an expression. For example, an expression tree can be used to represent mathematical formula x < y where x, < and y will be represented as an expression and arranged in the tree like structure. Expression tree is an in-memory representation of a lambda expression.
Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y . You can compile and run code represented by expression trees.
An expression tree is basically a binary tree which is used to represent expressions. In an expression tree, internal nodes correspond to operators and each leaf nodes correspond to operands. Here is a C++ program to construct an expression tree for a prefix Expression in inorder, preorder and postorder traversals.
You could use a method like here:
string myFunction(Object obj){
//here your if-else...
}
LabelCriteria = x => myFunction(x);
You must use the conditional operator:
LabelCriteria = x => true ? "Cash" : " ";
It may be that the compiler is modifying the expression because of constant folding, however, since the condition is a constant expression (true
). Try using a variable there and see what happens.
you could construct an expression tree explicitly with Expression API, refer to https://msdn.microsoft.com/en-us/library/bb397951.aspx
here's the code for your problem:
ParameterExpression x = Expression.Parameter(typeof (object), "x");
ConditionalExpression body = Expression.IfThenElse(
Expression.Constant(true),
Expression.Constant("Cash"),
Expression.Constant(" ")
);
LabelCriteria = Expression.Lambda<Func<object, string>>(body, x);
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