Reputation: 91
I have a method that needs to return true or false based upon a string expression that is passed in to it. The string expression could look like:
("ASDF"=="A" || "BED"!="BED") && (5>=2)
or any valid C# expression that evaluates to a Boolean result. I only need to support basic string and math comparison operators plus parentheses. I have tried NCalc but when I pass it this:
"GEN"=="GEN" || "GEN"=="GENINTER"
it generates the error System.ArgumentException: Parameter was not defined (Parameter 'GEN') at NCalc.Domain.EvaluationVisitor.Visit(Identifier parameter)
when I use the following code:
NCalc.Expression e = new(filterExpression, EvaluateOptions.IgnoreCase); var filterResultObject =e.Evaluate();
Any thoughts appreciated on how to evaluate an arbitrary expression since I will not know the expression until run time.
Greg
Upvotes: -1
Views: 640
Reputation: 11342
Another option is to use DynamicExpresso library. Example usage:
var interpreter = new Interpreter();
bool result = (bool)interpreter.Eval("\"GEN\" == \"GEN\" || \"GEN\" == \"GENINTER\"");
They also have an online tool to test expressions.
Upvotes: 0
Reputation: 704
For your example you can use NFun package like this:
string str = "\"ASDF\"==\"A\" || \"BED\"!=\"BED\") && (5>=2)"
bool result = Funny.Calc<bool>(str)
Upvotes: 0
Reputation: 91
I have found that NCalc will properly evaluate the strings but only if they are single quoted such as !('GEN'=='GEN'). If the strings are double quoted, the error is thrown.
Upvotes: 0