Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...