You don't have to do anything with formula, you can pass variables as DataColumn
s:
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];
}
}
Usage:
var variables = new Dictionary<string, object> {
{ "d", 1},
{ "dft", 32},
{ "t", 4},
};
var result = Compute("d + dft-t", variables);
Console.Write(result);
Outcome:
29
If you insist on string processing you can try regular expressions to replace smartly:
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);
Outcome:
1 + 32-4
Pattern Explained:
\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
Edit: To get dictionary from variables_cache
you can use Linq:
IDictionary<string, object> dict = variables_cache
.ToDictionary(item => item.name, (object) (item.value));
tehcnically, you don't need dictionary and can easily use you own structure:
// 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];
}
}