Check if condition in string format in c#

2019-08-04 14:07发布

问题:

I am not sure weather its possible or not but I have to do it in my project somehow. I am getting one condition in string format like:

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 condition I am getting from db and I have value of param1, param2 and param3 in my code. Now I have to check this condition in a if statement weather its true of false and show result accordingly.

I try like replacing param1, param2, param3 with actual value lets say 69, CA, 22. So the string will look like:

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 to convert it in bool also but its not working.

Please let me know if there is any way or else I need to hardcode it? One more thing, condition might very, like sometimes it will come with 2 variable or sometimes with four.

回答1:

if you really need to test condition in application and if you can modify condition string a bit further, i can suggest a hack with DataTable. DataTable can eval 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;
    }
}


回答2:

C# (and other compiled .NET languages) is not "JIT", interpreted languages, nor does it do automatic type conversion (number != string). You'd have to analyze and process the string yourself if you want to do it from within C#.

But... Since you're already using a database, and by the look of it it processes SQL, you could simply delegate the task to the database and get the end result instead of the condition string.

Call a stored procedure that accepts your params and the key to query string and have it return the boolean result, or prepend the injected string you created (after injecting the param values) with a SELECT and process that with the DB engine again. Just make sure you know you want to injecting dangerous user input, or you'll open yourself up for SQL injection attacks.