Update - I was trying to evaluate an expresion in C# using the
DataTable.Compute() method and found that instead of using
ternary operator(?,: ), I should've used the
IFF(expression, truepart, falsepart). So I'm trying to convert the whole expression into the IFF format and need a little help to construct the logic.
static string IIFApproach()
{
DataTable dt = new DataTable();
string formula = "If(1 > 20) then((1 / 1) > 10 and(1 / 1) <= 3500) else (If(1 equals 0) then TRUE else FALSE )";
formula = formula
.Replace("If", "IIf(")
.Replace("then", ",")
.Replace("equals", "=")
.Replace("else", ",");
formula = dt.Compute(formula, "").ToString();
return formula;
}
I'm struck at the opening and closing of the IFF parenthesis. I have tried to add the starting parenthesis at the time of replacement [.Replace("If", "IIf(")] but I'm unable to put the closing parenthesis at the end of the expression. I know that it can be done using stacks but as I confess I'm not good with data structures. Please help me to construct a logic.
Old Question - I'm trying to evaluate an expression using the
Compute()
method of
DataTable
and it shows an error "
Cannot interpret token ?
". My expression contains ternary operator and i need to solve the expression manually (without using nCalc or other tools). Is there any inbuilt microsoft functionality or any other approach to solve this expression.
DataTable dt = new DataTable();
var result = dt.Compute(" ( 1 > 20 ) ? (( 1 / 1 ) > 10 && ( 1 / 1 ) <= 3500 ) : ( ( 1 == 0) ? 1 : 0 )", null);
Console.WriteLine("The result is" + result);