首页 > 解决方案 > 在 SQL Server 中存储计算表达式并在 C# 中对其进行评估?

问题描述

我想将简单的数学计算(公式)存储在数据库中,然后以某种方式解释和计算它。

问题是,我不知道该怎么做。所以我可能有这样的事情:

CREATE TABLE Values (
    [ValuesId] [int] NOT NULL PRIMARY KEY,
    [Name] [nvarchar](250) NOT NULL,
    [Value] [decimal](18, 2) NOT NULL
)

而且,对于计算,我可能想使用这样的东西:

CREATE TABLE Calculations (
    [Id] int NOT NULL PRIMARY KEY,
    [Calc] [nvarchar](100) NOT NULL
)

Calc 列是我通常想要存储计算的地方,其中计算中的每个数字都表示 Value 表(操作数)的 ValuesId 的 Id。例如,典型的 Calc 值应该是这样的:'274 + 277 - 273',因此该值的计算方式是:从 Values 表中取出 id 为 274 的“Value”,将其添加到相应的“Value”中' 的 id 275,最后减去相应的 'Value' 的 id 277。这些计算可以包含所有 4 个基本运算符(+、-、*、/),不幸的是,操作数的数量可能会有所不同。

最终目标是评估存储的表达式。

如果您可以提供一些解决此问题的代码,那就太好了,但是给我正确的方向也很有帮助。

标签: c#sql-serverformula

解决方案


我最终将正则表达式与数据表结合使用。

//id is the primary key of whatever data I want
 string calculations = calculationsService.GetById(id).Calc;

//extract the ids into an array
 string[] numbers_in_formula = Regex.Split(calculations, @"[^0-9\.]+").Where(c => c != "." && c.Trim() != "").ToArray();

//substitute the ids to values

        foreach(string number in numbers_in_formula)
        {

                    //lets search data value
                    decimal tempvalue = Values.Find(Convert.ToInt32(number)).Value;

                    //replace the id with the value in the string 
                    calculations = calculations.Replace(number, tempvalue.ToString(CultureInfo.InvariantCulture));
                
            }
        }
        
        // compute that
        using (DataTable dt = new DataTable())
        {
            decimal result = (decimal)dt.Compute(calculations, "");

        }

当然,如果除了 id 之外还需要数字,则应使用令牌对 id 进行签名,以将它们与值区分开来。


推荐阅读