2017-05-15 15 views
1

計算されたDatatableの列のベースを他の文字列の文字列で更新する方法が必要です。例えば :DataTableの動的計算カラム

 
x   y   FormulaCol   ComputedCol 
------------------------------   ----------- 
2   5   x+y    7 
2   5   x*y    10 

私はforループを使用して、結果列を計算することができることを知っている:

for (int i = 0; i < DT.Rows.Count; i++){ 
string formula=DT.Rows[i]["FormulaCol"].ToString().Replace("x",DT.Rows[i]["x"]).Replace("y",DT.Rows[i]["y"]) 
DT.Rows[i]["ComputedCol"] =(int)DT.Compute(formula , "") 
    } 

は、任意のより良い方法はありますか?

+1

? –

+0

forループなしの自動計算された方法またはforループなしの置換えなしの方法。 – Farhawd

答えて

3

あなたはループを使用しない場合は、これを試して...

DT = DT.AsEnumerable() 
     .Select(
       row => 
       { 
        row["ComputedCol"] = (int)DT.Compute(row["FormulaCol"].ToString() 
          .Replace("x", row["x"].ToString()) 
          .Replace("y", row["y"].ToString()), ""); 
        return row; 
       } 
       ).CopyToDataTable<DataRow>(); 
1

シンプルですが、長いソリューション:
これはあなたのテーブルは次のようになります方法です 、

 
x   y   FormulaCol   ComputedCol 
------------------------------   ----------- 
2   5   +    7 
2   5   *    10 

とあなたのコード:このことができます

for (int i = 0; i < DT.Rows.Count; i++){ 
    switch(DT.Rows[i]["FormulaCol"].ToString()){ 
     case "+": 
      int formula=(int) DT.Rows[i]["x"] + (int) DT.Rows[i]["y"]; 
      DT.Rows[i]["ComputedCol"] = formula; 
      break; 
     case "-": 
      int formula=(int) DT.Rows[i]["x"] - (int) DT.Rows[i]["y"]; 
      DT.Rows[i]["ComputedCol"] = formula; 
      break; 
     case "*": 
      int formula=(int) DT.Rows[i]["x"] * (int) DT.Rows[i]["y"]; 
      DT.Rows[i]["ComputedCol"] = formula; 
      break; 
     case "/": 
      int formula=(int) DT.Rows[i]["x"]/(int) DT.Rows[i]["y"]; 
      DT.Rows[i]["ComputedCol"] = formula; 
      break; 
    } 
} 

願っています!どのような方法より良いに

+0

サンプルとしてx + yだけを使用しています。ユーザーが式を入力できる数式の列が必要でした。 – Farhawd

0
for (int i = 0; i < DT.Rows.Count; i++){ 

string formula=DT.Rows[i]["FormulaCol"].ToString() 
for (int j = 0; j < DT.Columns.Count; j++){ 

furmula=formula.Replace(DT.Columns[j].Name ,DT.Rows[i][j].ToString()) 

} 

DT.Rows[i]["ComputedCol"] =(int)DT.Compute(formula , "") 
}