Conditional expression evaluation

I have a script in which I save my if conditions in the database as a string. For instance:

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

OR

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

Now I want to evaluate that the user enters the condition syntactically correctly. This is an example of incorrect syntax:

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

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

Like ours in the Evaluate Query Expression. Perhaps you can use an expression. But how? Need help in this regard.

+5
source share
3 answers

Take a look at NCalc . This is the basis for evaluating mathematical expressions.

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

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

Although you can also detect syntax errors before evaluating using the method HasErrors().

Expression e = new Expression("a + b * (");
if(e.HasErrors())
{
    Console.WriteLine(e.Error);
}
+3
source

Visual studio , , , .

, # sql # ( , , #).

, , SQL Builder .

, , , ( ).

EDIT: , SelectQueryBuilder .

0

I found this solution

evaluate the arithmetic expression stored in a string (C #)

DECISION:

string conditiontext = "(([age] >= 28) && ([nationality] == \"US\"))";
conditiontext = conditiontext.Replace("[age]", 32)
                             .Replace("[nationality]","US");

/*VsaEngine*/
var engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();

/** Result will be either true or false based on evaluation string*/
var result = Microsoft.JScript.Eval.JScriptEvaluate(conditiontext, engine);

[Note. This interface is out of date. But it evaluates any arithmetic expressions and C # expressions]

0
source

All Articles