14

Is it possible to convert a string expression into a boolean condition?

For example, I get the following string:

var b = "32 < 45 && 32 > 20"

I would like to create a bool expression out of this and invoke it. The string representation is also flexible (to make it more fun), so it allows ||, &&, ().

1

7 Answers 7

8

Have a look at Flee (Fast Lightweight Expression Evaluator) on CodePlex.

Sign up to request clarification or add additional context in comments.

2 Comments

Man, what an incredible library! It worked perfectly for me. Thank you very much for your tip.
Thanks for pointing out this library @Richard, this is exactly what I needed!!!
5

I would use Irony, the .NET language kit. You could construct a simple grammar with Irony and then parse the string into executable command. There's a decent example of an arthmetic grammar in this tutorial and in the Expression Grammar Sample, its a pretty common request ;)

I definitely suggest using a proper compiler as opposed to Regex or a roll your own approach - it will be much more extensible if you ever want to add more rules.

Comments

2

If it follows all C# expression rules then compile it as dynamic code as per http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm

3 Comments

How fast is that? I imagine it being quite slow
Not fast at all. Basically you invoke the C# compiler, which emits the IL of the expression, which is then wrapped in a method, then in a class, then in a dynamic assembly which is loaded into the current AppDomain, then you invoke the method through reflection to get the evaluation result. But it's a breeze to integrate, if it's just for a proof of concept or something...
Yes, I know how it works. I just wanted to point out that it would be a really slow way to do it
1

If you're dealing with relatively simple mathematical expressions then a straightforward implementation of the shunting-yard algorithm should do the trick.

Comments

1

Take a look at my library, Proviant. It's a .NET Standard library using the Shunting Yard algorithm to evaluate boolean expressions. You could also implement your own grammar.

1 Comment

Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?
0

I think creating an interpreter for this string would not take too long time.

http://www.industriallogic.com/xp/refactoring/implicitLanguageWithInterpreter.html

here you can find information about design that can be used to create it.

Comments

0

You could take a look at JINT (Javascript Interpreter for .NET) http://jint.codeplex.com/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.