c# - 在 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 个基本运算符(+、-、*、/),不幸的是,操作数的数量可能会有所不同。
最终目标是评估存储的表达式。
如果您可以提供一些解决此问题的代码,那就太好了,但是给我正确的方向也很有帮助。
解决方案
我最终将正则表达式与数据表结合使用。
//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 进行签名,以将它们与值区分开来。
推荐阅读
- phpstorm - MantisBT 和 PhpStorm 的问题
- java - 在 Java 中的 Arraylist 中创建 Arrylist
- php - 正则表达式 (PHP) 删除除引号之间的所有水平空格(“”和 '')(包括转义引号)
- swift - 不能在属性初始化器中使用实例成员“月”;属性初始化程序在“自我”可用之前运行
- html - 在 CSS 网格内放置文本和按钮
- php - 将列的总和与 PDO 中具有嵌套选择查询的另一个表中的列进行比较
- javascript - Calculation on fields
- django - Passing keyword argument into formset that is extended from BaseFormSet
- c# - C# TCP 套接字高网络使用率
- php - 如何访问数组中的对象