数据库中的数据表计算字符串

时间:2018-12-23 09:31:34

标签: c# datatable

我想要实现的是从数据库获取公式表达式并在运行时执行它。阅读我发现的内容之后;

    // Consider these values are coming from the DB
        int voltageln1 = 220;
        int voltageln2 = 220;
        int voltageln3 = 220;
        int currentln1 = 10;
        int currentln2 = 10;
        int currentln3 = 10;


        string formula = $"(({voltageln1}*{currentln1}*{0.85})+({voltageln2}*{currentln2}*{0.85})+({voltageln3}*{currentln3}*{0.85}))";
        DataTable dt = new DataTable();
        double result = Convert.ToDouble(dt.Compute(formula, ""));
        MessageBox.Show("Result:" + result);

当字符串公式中预先带有$符号时,上述代码可以正常工作。

但是我从数据库收到的信息如下,其中前面没有$符号。

string thatcamefromtheDB = "(({voltageln1}*{currentln1}*{0.85})+({voltageln2}*{currentln2}*{0.85})+({voltageln3}*{currentln3}*{0.85}))";

是否可以通过某种方式添加$符号或格式化文本?

1 个答案:

答案 0 :(得分:0)

您可以尝试Double.Parse:

  double data= ((Double.Parse(voltageln1)*Double.Parse(currentln1)*0.85)+(Double.Parse(voltageln2)*Double.Parse(currentln2)*0.85)+(Double.Parse(voltageln3)*Double.Parse(currentln3)*0.85))";