2016-11-18 78 views
0

如何執行此任務?如何替換二維字符串數組中的值

int Amount, x=1000,y=200; 
string BasedOn="x*12/100+y*5/100"; 
//In place of x and y in BasedOn I want to replace with x,y values like (1000*12%+200*5%) 
//and the calculated result(130) should be assigned to Amount variable 

現在,我拆支持算法FMP串

string[][] strings = BasedOn 
    .Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries) 
    .Select(w => w.Split('*').ToArray()) 
    .ToArray(); 

下一步做什麼?請幫幫我。

回答

1

我做你的代碼更加靈活

static void Main(string[] args) 
    { 
     Dictionary<string, object> variables = new Dictionary<string, object>(); 
     variables.Add("x", 1000); 
     variables.Add("y", 200); 
     string equation = "x*12/100+y*5/100"; 
     var result = Calculate(variables, equation); 
    } 
    static object Calculate(Dictionary<string, object> variables, string equation) 
    { 
     variables.ToList().ForEach(v => equation = equation.Replace(v.Key, v.Value.ToString())); 
     return new DataTable().Compute(equation, string.Empty); 
    } 
0

您可以看看DataTable.Compute方法。 它可以像這樣使用你的案件:

using System.Data; 

DataTable dt = new DataTable(); 
var Amount = dt.Compute("1000*12%+200*5%",""); 

對於替換「X」和「Y」用數值如果要替換字符串,你可以使用與string.replace

0

,並計算結果,你可以這樣做:

int Amount, x=1000,y=200; 
string BasedOn=$"{x}*12/100+{y}*5/100"; 

DataTable dt = new DataTable(); 
var v = dt.Compute(BasedOn,""); 

v將是你的結果(130)。

編輯:你必須替換你的%除以100,因爲數據表認爲它是一個mod運算符。

+0

此代碼會拋出異常。 – mybirthname

+0

@mybirthname固定。 –

+0

@UmutSeven在var v = dt.Comput(BasedOn,「」)處得到SyntaxExceptionError(無法解釋位置2處的標記''') –

0

隨着DataColumn.Expression

int Amount, x = 1000, y = 200; string BasedOn = "x*12%+y*5%"; 

var dt = new DataTable(); 
dt.Columns.Add("x", typeof(int)); // in Visual Studio 2015 you can use nameof(x) instead of "x" 
dt.Columns.Add("y", typeof(int)); 
dt.Columns.Add("Amount", typeof(int), BasedOn.Replace("%", "/100")); // "x*12/100+y*5/100" ("%" is considered modulus operator) 

Amount = (int)dt.Rows.Add(x, y)["Amount"]; // 130 

隨着RegEx.ReplaceDataTable.Compute

string expression = Regex.Replace(BasedOn.Replace("%", "/100"), "[a-zA-Z]+", 
    m => (m.Value == "x") ? x + "" : (m.Value == "y") ? y + "" : m.Value); // "1000*12/100+200*5/100" 

Amount = (int)(double)new DataTable().Compute(expression, ""); // 130.0 (double)