在c#中检查字符串格式是否有条件 [英] Check if condition in string format in c#

查看:200
本文介绍了在c#中检查字符串格式是否有条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定天气是否可能,但我必须以某种方式在我的项目中这样做。
我得到一个字符串格式的条件,如:

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')";

我从db获得这个条件,我的代码中有param1,param2和param3的值。现在我必须在if语句中检查这个条件,看看它是否为true,并相应地显示结果。

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.

我尝试用实际值替换param1,param2,param3让我们说69,CA,22。因此字符串将如下所示:

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')";

并尝试将其转换为bool但它不起作用。

and try to convert it in bool also but its not working.

如果有任何办法,请告诉我,否则我需要对其进行硬编码?
还有一件事,条件可能非常,有时它会带有2个变量或有时带有4个变量。

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.

推荐答案

如果你真的需要在应用程序中测试条件,如果你可以进一步修改条件字符串,我可以建议使用 DataTable 进行黑客攻击。 DataTable 可以评估您的字符串:

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:

演示

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;
    }
}

这篇关于在c#中检查字符串格式是否有条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆