我試圖用文本字串中的值替換變數,這是一個數學運算式。
math_Expresion = d dft-t
到其當前值:
1 32 - 4
然后用一個DataTable()計算出來
var result = new DataTable().Compute(math_Expresion, null);
但是,如果作為名稱的變數包含另一個變數,則它不起作用,例如
a = 1
aa = 22
d = a aa
d.Replace ("a", a)
d.Replace ("aa", aa)
return 1 11 not 1 22
混淆名稱。有沒有辦法用它們的值替換名稱而不跳過它們、某些ReplaceExacly()函式或類似的東西來避免這種不適?
實際代碼:
for (int i = 0; i < variables_cache.Count; i )
{
if (math_expresion.Contains(variables_cache[i].name))
{
math_expresion = math_expresion.Replace(variables_cache[i].name, variables_cache[i].value);
}
}
var result = new DataTable().Compute(math_expresion, null);
uj5u.com熱心網友回復:
您不必對公式執行任何操作,您可以將變數作為DataColumns傳遞:
private static object Compute(string formula,
IDictionary<string, object> variables = null) {
// using - don't forget to Dispose table which is IDisposable
using (DataTable table = new DataTable()) {
// If we have variables...
if (variables != null)
foreach (var pair in variables) // ... we create columns
table.Columns.Add(pair.Key, pair.Value.GetType()).DefaultValue = pair.Value;
// last column is computation result
table.Columns.Add().Expression = formula;
// result is the value of the last (computed) column
return table.Rows.Add()[table.Columns.Count - 1];
}
}
用法:
var variables = new Dictionary<string, object> {
{ "d", 1},
{ "dft", 32},
{ "t", 4},
};
var result = Compute("d dft-t", variables);
Console.Write(result);
結果:
29
如果您堅持字串處理,您可以嘗試使用正則運算式巧妙地替換:
using System.Text.RegularExpressions;
...
var variables = new Dictionary<string, object> {
{ "d", 1},
{ "dft", 32},
{ "t", 4},
};
var formula = "d dft-t";
formula = Regex.Replace(
formula,
@"\b\p{L}[\p{L}\d_]*\b",
m => variables.TryGetValue(m.Value, out var value)
? value?.ToString()
: m.Value);
Console.Write(formula);
結果:
1 32-4
模式解釋:
\b - word border
\p{L} - letter (unicode one, we can use, say, cyrillic letters as well)
[\p{L}\d_]* - zero or more letters, digits, or _
\b - word border
編輯:要從中獲取字典,variables_cache您可以使用Linq:
IDictionary<string, object> dict = variables_cache
.ToDictionary(item => item.name, (object) (item.value));
技術上,您不需要字典并且可以輕松使用自己的結構:
// Assuming that MyVariable has Name and Value properties or fields
private static object Compute(string formula,
IEnumerable<MyVariable> variables = null) {
// using - don't forget to Dispose table which is IDisposable
using (DataTable table = new DataTable()) {
// If we have variables...
if (variables != null)
foreach (var pair in variables) // ... we create columns
table.Columns.Add(pair.Name, pair.Value.GetType()).DefaultValue = pair.Value;
// last column is computation result
table.Columns.Add().Expression = formula;
// result is the value of the last (computed) column
return table.Rows.Add()[table.Columns.Count - 1];
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374137.html
