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

和自甴很熟 提交于 2019-12-12 07:19:51

问题


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:


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




回答2:


You could use Zentrum.

Full disclaimer: I wrote it!




回答3:


we're using http://simproexpr.codeplex.com/




回答4:


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 and Not operators and parentheses are allowed.



来源:https://stackoverflow.com/questions/8476422/logic-evaluator-in-c-sharp-evaluate-logical-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!