Logic Evaluator in c# (Evaluate Logical (&& ,|| ) expressions)
Asked Answered
S

2

7

In my project there is a Logic evaluation section, it take input as a string which contains logical expressions (true/false) .

I want to evaluate this string and return a final Boolean value.

string Logic="1&0|1&(0&1)"
//string Logic="true AND false OR true AND (false AND true)"

This will be my Logic. The length might increase.

Is there any way to Evaluate this expression from LINQ / Dynamic LINQ ?

Sublittoral answered 12/12, 2011 at 15:11 Comment(4)
language integrated query != lexical parsing/evaluationHundredth
Any reason you're using a single bitwise AND but a short-circuiting logical OR in the example?Prenotion
@ Kieren Johnstone : Oh sorry .. nothing like that... I will edit it.. :)Sublittoral
If it is okay to use a librarie take a look here.Nippon
A
16

a way without any third party libraries is to use a DataTable with expression.

There you have even the possibility to evaluate on other result value types than just boolean.

System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("", typeof(Boolean));
table.Columns[0].Expression = "true and false or true";

System.Data.DataRow r = table.NewRow();
table.Rows.Add(r);
Boolean result = (Boolean)r[0];

the expression syntax is not identical with your example but it does the same thing. An advantage is that its 100% .NET framework contained --> Microsoft managed. The error handling is not bad neither. Exceptions for missing operators etc...

available operators

Anastomosis answered 12/12, 2011 at 15:28 Comment(2)
but this is taking 7 milli seconds... my existing code takes less than 1 milli sec.... i want to reduce thisSublittoral
i dont think its the most performant option... but has quite some possibilitiesAnastomosis
A
13

This is even shorter than the solution given by @fixagon:

System.Data.DataTable table = new System.Data.DataTable();
bool result = (bool)table.Compute("true and false or true", "");

True, False, Not operators, as well as parentheses are allowed.

Arleyne answered 20/7, 2019 at 9:13 Comment(1)
Works for me (upvote). As an addition: also parentheses are allowed in order to change precedence.Indubitability

© 2022 - 2024 — McMap. All rights reserved.