"Coco" <an*******@discussions.microsoft.com> wrote in message
news:05****************************@phx.gbl...
Hi!
Does c# has any class method that will be able to evaluate
a given string e.g ((True && False) || (True && True)) and
return the result in boolean for this case is true
Thanks!
Here's a simple class that can do it. It's not very efficient--for better
speed and memory use you'd want to use something else. Look up "infix
evaluation" for some more ideas. But this one is short and sweet and it's
fun to watch the expression cave in on itself each time through the loop.
You can easily extend it to include ==, != and other operators.
class BooleanEvaluator
{
public static bool Evaluate(string expression)
{
expression =
expression.ToLower(System.Globalization.CultureInf o.InvariantCulture);
expression = expression.Replace("false", "0");
expression = expression.Replace("true", "1");
expression = expression.Replace(" ", "");
string temp;
do
{
temp = expression;
expression = expression.Replace("(0)", "0");
expression = expression.Replace("(1)", "1");
expression = expression.Replace("0&&0", "0");
expression = expression.Replace("0&&1", "0");
expression = expression.Replace("1&&0", "0");
expression = expression.Replace("1&&1", "1");
expression = expression.Replace("0||0", "0");
expression = expression.Replace("0||1", "1");
expression = expression.Replace("1||0", "1");
expression = expression.Replace("1||1", "1");
}
while (temp != expression);
if (expression == "0")
return false;
if (expression == "1")
return true;
throw new ArgumentException("expression");
}
}