C# .NET - Code in C# to check the grammar of logical expression

Asked By Rishi Mishra on 28-Apr-20 02:40 PM

Hi ,

I am generating below grammar rules dynamically through UI interface which contains different operators {‘<’,’<=’,’>’,’>=’,’In’,’!=’,’=’} and connectors {‘AND’,’OR’} with nested parentheses i.e. ‘(‘,’)’ etc.

( Amount >= 12522 And Amount <= 145111 And (City IN ( 1,2,3,4 ) ) And Age > 25 And Gender IN (‘M’,’F’) ).

 

I want to check the grammar of above rule syntactically including the valid values of connectors and operators. Also, nested parentheses count should be equal and logical.

So, following rules to be considered as wrong rules

( Amount >= 12522 AndAnd Amount <= 145111 And (City IN ( 1,2,3,4 ) ) And Age > 25 And Gender IN (‘M’,’F’) ). [Two Invalid And Operators]

 

((( Amount >= 12522 And Amount <= 145111 And (City IN ( 1,2,3,4 ) ) And Age > 25 And Gender IN (‘M’,’F’) ).[Parenthesis count is not equal].

 

Can anyone share the logic in C# so that I can consume it in my application ?

 

Thanks,

Robbe Morris replied to Rishi Mishra on 30-Apr-20 03:24 PM
I don't see anyone spending a few hours trying to write your code for you.

You could spend a ton of time writing a parser or you could create a table variable in SQL with all your field names and their proper data types.  Then, do

"select * from @YourTableVariableName where " + your comparison string here.  Run the query.  That would put the onus  on the database server to either return values or give information about the error.  Of course, you'd need to run this under a sql user with SELECT only permissions and tried to do some other things to secure it.  Perhaps, you could use the querying mechanism against a DataSet in .NET to avoid the SQL security issues.  Just load the dataset up and query against it directly.  Maybe...

Kind of a solution out of left field, but if you needed something at least functional at validating this (plus actually give you data if the comparison string is right) to get version1 of your product out the door, it might be useful.

Spreadsheetgear.com and Excel might also be an alternate as part of a similar solution.