I have a C# Console Application project.
I have a logical expression that is stored in database as nvarchar.
For example, the stored expression is: ((34 > 0) || (US == ES)) && (4312 = 5691)
While my application running, I want to retrieve the expression and evaluate it so that the result will be true or false.
How can I do it at runtime?
You can parse the expression into the .NET
Expression
class and compile and run it in order to get the result.The class already supports all the logical operations you have in your example, though it appears to be ambiguous (you are using both
==
and=
in a very similar manner).You will have to write your own parser/converter though.
Here's a rather unusual solution, involving JScript:
Create a JScript class with the following code:
Compile it into a DLL:
In your C# project, reference JsMath.dll and Microsoft.JScript.dll
Now you can use the
Eval
method as follows:Benefits:
Drawbacks: