0

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
}
Dbl
  • 5,634
  • 3
  • 41
  • 66
  • https://stackoverflow.com/questions/5029699/c-sharp-convert-string-expression-to-a-boolean-expression – Arslan Ali Aug 06 '18 at 00:00
  • It really would help if you explained [why you need to do this](https://meta.stackexchange.com/questions/66377). – Dour High Arch Aug 06 '18 at 00: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 – TheGeneral Aug 06 '18 at 00:06

2 Answers2

0

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

Muhammad Azeez
  • 926
  • 8
  • 18
0

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.

Arslan Ali
  • 450
  • 4
  • 12