(Evaluate Logical (&&,||) expressions) Logic Evaluator in C#

boolean-logic c# dynamic-linq linq logical-operators

Question

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 ?

1
4
12/13/2011 12:03:35 PM

Accepted Answer

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

12
12/12/2011 3:47:05 PM

Popular Answer

You could use Zentrum.

Full disclaimer: I wrote it!



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow