Check condition in string format in C #

I'm not sure if the weather is possible or not, but I have to somehow do it in my project. I get one condition in string format, for example:

string condition = "(param1='69' OR param1='66' OR param1='21' OR param1='93') AND (param2='FL' OR param2='WA) AND (param3!='31' AND param3!='19')"; 

This is the condition I get from db, and I have the value param1, param2 and param3 in my code. Now I have to check this condition in the if statement so that its true value is false and show the result accordingly.

I am trying how to replace param1, param2, param3 with the actual value, say 69, CA, 22. So the line will look like this:

 condition = "(69='69' OR 69='66' OR 69='21' OR 69='93') AND (CA='FL' OR CA='WA) AND (22!='31' AND 22!='19')"; 

and try converting it to bool, but it does not work.

Please let me know if there is any way, or do I need to hard record it? One more thing: a condition can be very strong, for example, sometimes it will have 2 variables, and sometimes four.

+1
source share
2 answers

if you really need to check the condition in the application, and if you can change the status bar a bit, I can suggest hacking with a DataTable . DataTable can parse your string:

demo

 public class Program { public static void Main(string[] args) { // modified string ! // "!=" -> "<>"; CA -> 'CA' string condition = "('69'='69' OR '69'='66' OR '69'='21' OR '69'='93') AND ('CA'='FL' OR 'CA'='WA') AND ('22'<>'31' AND '22'<>'19')"; Console.WriteLine(TestCondition(condition)); // print FALSE because ('CA'='FL' OR 'CA'='WA') is FALSE } public static bool TestCondition(string c) { var dt = new DataTable(); dt.Columns.Add("col"); dt.Rows.Add("row"); // hack // c is constant and doesn't depend on dt columns // if there are any rows, c is TRUE var rows = dt.Select(c); return rows.Length > 0; } } 
+4
source

C # (and other compiled .NET languages) is not "JIT", interpreted languages ​​and does not perform automatic type conversion (number! = String). You will have to parse and process the string yourself if you want to do this from within C #.

But ... Since you already use the database, and in appearance it processes SQL, you can simply delegate the task to the database and get the final result instead of the condition line.

Call the stored procedure, which takes your parameters and the key to the query string, and whether it returns a logical result or adds the entered string that you created (after entering the parameter values) using SELECT and process it using the database engine again. Just make sure you know that you want to enter dangerous user input, or you will open yourself up for SQL injection attacks.

0
source

Source: https://habr.com/ru/post/1271727/


All Articles