0

I have to convert a string to bool and evaluate the string condition. For example:

string condition = "8 > 9 || !8";

then the condition has to evaluate and return true;

if string condition = "!8"; then condition has to return true.

Suggest me how to evaluate the condition.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Kalyani Reddy
  • 131
  • 10
  • It depends on how reliable the structure of the string is. How many different operators do you expect to have to process?. What code have you written so far? – ste-fu Feb 17 '20 at 11:31
  • 3
    What have you tried so far? – Pavel Anikhouski Feb 17 '20 at 11:31
  • it seems like what you're really after here is an runtime expression parser and evaluator; that *isn't really a thing built into .NET* directly, but a range of tools exist. Or depending on the complexity of the expressions you need to parse, it is *usually* relatively easy to write them yourself, if you're used to things like AST evaluation. – Marc Gravell Feb 17 '20 at 11:32
  • Good exercise for Stack – Prasad Telkikar Feb 17 '20 at 11:32
  • btw; it isn't clear to me what `!8` means, as a boolean; is that meant in a C-style "zero is false, non-zero is true" way? – Marc Gravell Feb 17 '20 at 11:33
  • That's essentially some kind of parser, which will read your equations, determine operators and left/right side operands, have some kind of validation. There is no short answer to that. – SᴇM Feb 17 '20 at 11:33
  • @ste-fu , || , &&, !, <, <=, >, >= are the operators i have. Upto to now i just resolved the string values in place of 8 and 9. – Kalyani Reddy Feb 17 '20 at 11:33
  • I have a condition with registry keys like "REGISTRYVERSION > CURRENTVERSION OR NOT REGISTRYVERSION". I resolved the registry key values like the above condition resolved to 01.00.00.000 > 02.00.00.000 || !01.00.00.000.. Can some one suggest me how to resolve this condition and return bool value – Kalyani Reddy Feb 17 '20 at 11:36

2 Answers2

2

Generally, if you want to evaluate C# code during runtime, you can use the .NET Compiler Platform (Roslyn) via the Microsoft.CodeAnalysis.CSharp.Scripting Nuget package.

BTW, I found this right here in stack overflow: How can I evaluate a C# expression dynamically?

here's a solution to your specific requirement, assuming the only exception to valid C# expressions is treating !8 as boolean true (specifically "!8" preceded or followed followed by any other character is forbidden).

private async Task<bool> ProcessExpression(string expression)
    {
        var processedExpression = expression.Replace("!8", "true");
        return await CSharpScript.EvaluateAsync<bool>(processedExpression);
    }

And here's some test code for the above:

Task.Run(async () =>
        {
            var expresion = "8 > 9";
            var result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 < 9";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "!8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 > 9 || !8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");

            expresion = "8 > 9 && !8";
            result = await ProcessExpression(expresion);
            Console.WriteLine($"{expresion} : {result}");
        });

The output we get is:

8 > 9 : False 8 < 9 : True !8 : True 8 > 9 || !8 : True 8 > 9 && !8 : False

please note that this solution has a performance penalty and if this is a concert than you should look for other options such as writing a dedicated parser or look for 3rd party Nuget packages.

Assaf
  • 316
  • 2
  • 6
0

Try using the IValueConverter interface provided by .net

https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.ivalueconverter?view=netframework-4.8

Where u define 2 methods Convert and ConvertBack Each method takes a parameter of type object and return the type object

so u can input the string and return the Boolean. As for the conversion from a string to expression you can checkout this link https://expressiontree-tutorial.net/knowledge-base/5029699/csharp-convert-string-expression-to-a-boolean-expression which have the required code cleared out.

  • it really isn't obvious to me how `IValueConverter` would help here; that just defines an API - but, that isn't the problem here; the problem is implementing it! we could just as well forget about `IValueConverter` and say `bool DoTheThing(string expression) { /* TODO */ }` and we'd be in *exactly* the same position. The second link shown *is* relevant, though. – Marc Gravell Feb 17 '20 at 12:25
  • I didn't know exactly ur use case so i suggested the IValueConverter so u can use it in several situations like in xaml binding or any other usecase –  Feb 17 '20 at 12:39
  • this is an old link but it is discussing the same issue https://stackoverflow.com/questions/5029699/c-sharp-convert-string-expression-to-a-boolean-expression –  Feb 17 '20 at 12:39