将计算表达式存储在 SQL 服务器中并在 C# 中对其求值?
Store a calculation expression in SQL Server and evaluate that in 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 列是我通常要存储计算的地方,其中计算中的每个数字表示值 table(操作数)的 ValuesId 的 Id。例如,一个典型的 Calc 值应该是这样的:'274 + 277 - 273',因此该值的计算方法是:从 ID 为 274 的值 table 中获取 'Value',添加它到 id 275 的相应 'Value',最后减去 id 277 的相应 'Value'。这些计算可以包含所有 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, "");
}
当然,如果除了ids还需要数字,ids应该用token签名,以区别于值。
我想在数据库中存储简单的数学计算(公式),然后以某种方式解释和计算它。
问题是,我不知道该怎么做。所以我可能有类似的东西 这个:
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 列是我通常要存储计算的地方,其中计算中的每个数字表示值 table(操作数)的 ValuesId 的 Id。例如,一个典型的 Calc 值应该是这样的:'274 + 277 - 273',因此该值的计算方法是:从 ID 为 274 的值 table 中获取 'Value',添加它到 id 275 的相应 'Value',最后减去 id 277 的相应 'Value'。这些计算可以包含所有 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, "");
}
当然,如果除了ids还需要数字,ids应该用token签名,以区别于值。