-1

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){
}
Harshani
  • 649
  • 2
  • 9
  • 22
  • 1
    what you need is to write a logic to parse the string and return the final outcome of it based on the values of `item(s)` stored in some dictionary. – Chetan May 08 '23 at 02:21
  • We need more information. What format are the items? E.g. are they expressed in code? What language? Can you give some examples? – srk May 08 '23 at 02:28
  • please review below address,Maybe help your https://stackoverflow.com/questions/53844/how-can-i-evaluate-a-c-sharp-expression-dynamically – bingbing May 08 '23 at 02:45
  • 1
    Try Dynamic LINQ more details here: https://dynamic-linq.net/ – Sunil Shrestha May 08 '23 at 02:56
  • 1
    If you're really keen, you can use Roslyn. Great learning experience as well. – Skin May 08 '23 at 03:09

1 Answers1

3

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