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?
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.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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.