evaluate relational operator from a string

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



evaluate relational operator from a string



I have relational expressions stored in a database, that i have as strings in an iOS app. I would like to evaluate the conditions within the strings in C#, similar to the logic in the following psudo code:


string str1= "x > 0";
string str2= "y < 1";

int x = 1;
int y=0;

if(str1 && str2)

//do stuff





stackoverflow.com/questions/5029699/…
– Arslan Ali
Aug 6 at 0:00





It really would help if you explained why you need to do this.
– Dour High Arch
Aug 6 at 0:02





I agree, if they are simple numerical comparisons, and they are related to entities within your database, you could easily just do this in a table, with min max and enum to choose the variable your comparing with and so forth. this could be fast , server side, and easy as a LINQ / EF expression
– Saruman
Aug 6 at 0:06



enum




2 Answers
2



If the expressions are simple like the one in the example, then you can simply parse them. But if you have more complex expressions in mind, then I recommend taking a look at C# Expression Trees. The documentation does a good job of explaining it.



A much easier method would be to use library like: https://github.com/davideicardi/DynamicExpresso





Thank You. It was exactly what I needed
– Mike Wiggens 442
Aug 10 at 0:55





@MikeWiggens442 I'd appreciate it if you marked it as accepted answer then :D
– Encrypt0r
Aug 11 at 6:58





I am sorry, I had not checked this and did not see your comment. I marked you as accepted answer just now
– Mike Wiggens 442
Aug 28 at 7:28



Use Afk Expression Library (Afk link)
and try following code it will solve your problem as I sorted out.



Required NameSpace


using Afk.Expression;



Your code for sending expression as string to library evaluator


string str1 = "x > 0";
string str2 = "y < 1";

int x = 10;
int y = 0;
var st1=str1.Replace("x",x.ToString());
var st2 = str2.Replace("y", y.ToString());
if (Eval(st2) && Eval(st1))

//checked



Eval Method evaluate mathematical and conditional expression


bool Eval(string st)

ExpressionEval eval = new ExpressionEval(st);
return Convert.ToBoolean(eval.Evaluate().ToString());



As well read for more other libraries that you can utilize for your as such problems.





kindly marked as accepted
– Arslan Ali
Aug 6 at 1:04






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard