Reputation: 11871
I need to parse a string and produce a predicate (or expression, I'm not bothered) where the string takes the form:
"> 30"
I'd rather not write my own and there's a few libraries that do stuff like this - I've tried FLEE and NCalc but they seem to require the string to take the form "a > 30" and provide the value of 'a' as a paramter.
Is there a library that would allow me write something like
Func<int, bool> predicate = parser.Parse("> 30");
bool a = predicate(10); // false
bool b = predicate(40); // true
I need operators like <, >, =, etc, and support for OR and AND. And it's not just numbers I'm working with, strings and Enums are in the mix too.
Upvotes: 3
Views: 4380
Reputation: 44268
You could look into using the Dynamic Linq Library ScottGu has blogged about.
http://msdn.microsoft.com/en-US/vstudio/bb894665.aspx
if should let you do something like the following.
const string exp = "variable > 30";
var p = Expression.Parameter(typeof(int), "variable");
var e = DynamicExpression.ParseLambda(new[] { p }, null, exp);
bool a = (bool)e.Compile().DynamicInvoke(20);
bool b = (bool)e.Compile().DynamicInvoke(40);
or
Func<int, bool> predicate = (Func<int, bool>)e.Compile();
bool a = predicate(20);
bool b = predicate(40);
Upvotes: 8