Search code examples
c#string-parsingjsonparser

How to Parse a String to Logical Condition in C#


I am looking for a nuget package which could help me to parse a string to a logical condition in C#. I have a configuration file in json, where users can configure the logic as follows.

"condition": "(item1 AND item2) OR item3",

This should be parsed and used in a if condition as follows.

if((item1 && item2) || item3){
}

Solution

  • You should try the DynamicExpresso NuGet package. It allows you to interpret and execute strings as expressions in C#. This might work after you install that library:

    var yourString = "(item1 && item2) || item3";
    using DynamicExpresso;
    var i = new Interpreter();
    i.SetVariable("item1", true);
    i.SetVariable("item2", true);
    i.SetVariable("item3", true);
    bool result = i.Eval<bool>(yourString);
    

    Here's the GitHub page to learn its usage: https://github.com/dynamicexpresso/DynamicExpresso