Reputation: 153
I want to evaluate the string expression and convert the result to bool.
For example
string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;
the above expression has to evaluate and return true.
Can anyone suggest how to evaluate the expression and return bool value?
Upvotes: 3
Views: 2054
Reputation: 41
You can use the NCalc package. The code below produces "False"
using System;
using NCalc;
public class Program
{
public static void Main()
{
Expression e = new Expression("!((71 > 70) && (80 > 71)) || 72 < 71");
bool v = (bool)e.Evaluate();
Console.WriteLine(v.ToString());
}
}
.Net Fiddle: https://dotnetfiddle.net/02c5ww
Upvotes: 3
Reputation: 11364
I dont believe there is any built in expression solver that can be leveraged for this kind of expression evaluation. I would recommend Microsoft.CodeAnalysis.CSharp.Scripting to do the evaluation.
string expression = "!((71 > 70) && (80 > 71)) || 72 < 71";
bool output = CSharpScript.EvaluateAsync<bool>(expression).Result;
// -> false
Issues with your question
!((71 > 70) && (80 > 71)) || 72 < 71
!((true) && (true)) || false
!(true & true)
false
string express = "within quotes";
. Statement above in post (string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;
) is not a valid C# statement. Test snippet here at #dotnetfiddle
Upvotes: 2
Reputation: 61
If your requirement is to get expressoin output as string "true" then use this,
string expression = Convert.ToString(!((71 > 70) && (80 > 71)) || 72 < 71);
And if requirement is to get bool "true" then use this,
bool expression = !((71 > 70) && (80 > 71)) || 72 < 71;
But your expression is like it will return false, to make it true remove "!" as below,
string expression = Convert.ToString(((71 > 70) && (80 > 71)) || 72 < 71);
bool bool_expression = ((71 > 70) && (80 > 71)) || 72 < 71;
Upvotes: -1