Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Conditional Expression

Tags:

c#

I have a scenario in which I am saving my "if" conditions in database as a string. For example:

String condition = "(([age] >= 28) && ([nationality] == 'US'))";

OR

String condition = "([age] >= 28)";

Now, I want to evaluate that the user has input the condition syntactically correct. These are example of incorrect syntax:

String condition = "(([age] >= 28) && ([nationality] == 'US')"; //Missed ')' bracket

String condition = "[age] >= 28)"; //Missed Opening bracket '('

Like we have in Evaluate Query Expression. Might be Expression tress can be helpful. But how? Need help in this regard.

like image 683
Mehdi Avatar asked Oct 06 '22 13:10

Mehdi


1 Answers

Take a look at NCalc. It's a framework for evaluating mathematical expressions.

When the expression has a syntax error, the evaluation will throw an EvaluationException.

try
{
    new Expression("(3 + 2").Evaluate();
}
catch(EvaluationException e)
{
    Console.WriteLine("Error catched: " + e.Message);
}

Though, you can also detect syntax errors before the evaluation by using the HasErrors() method.

Expression e = new Expression("a + b * (");
if(e.HasErrors())
{
    Console.WriteLine(e.Error);
}
like image 165
david.s Avatar answered Oct 10 '22 02:10

david.s