Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string to produce predicate

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.

like image 696
RichK Avatar asked Jan 28 '26 01:01

RichK


1 Answers

You could look into using the Dynamic Linq Library ScottGu has blogged about.

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

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);
like image 189
Eoin Campbell Avatar answered Jan 30 '26 15:01

Eoin Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!