2

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?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Kalyani Reddy
  • 131
  • 10

3 Answers3

2

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

  • The expression will not evaluate to true. I dont know why you assume that and require that it does. After the execution of the above script, the resultant bool will be false.

!((71 > 70) && (80 > 71)) || 72 < 71
!((true) && (true)) || false
!(true & true)
false

  • you cannot declare a string without quotes; 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

Jawad
  • 11,028
  • 3
  • 24
  • 37
2

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

Belisarius
  • 31
  • 1
  • 5
-1

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;
amg
  • 61
  • 1
  • 6
  • The expression above is a dynamic expression.Then how the string can be converted to bool. I cannot directly assign the expression to bool variable. bool bool_expression = Convert.ToBoolean(string_expression) did not worked. Any more suggestions? – Kalyani Reddy Feb 19 '20 at 05:27
  • Sorry... I didn't read it properly and answered as per example. Good Luck... – amg Feb 20 '20 at 04:37