DataTable 动态计算列

DataTable dynamic computed column

我需要一种方法来根据其他字符串列中的字符串更新计算数据表的列。 例如:

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 , "")
  }

有没有更好的方法?

一个简单但漫长的解决方案:
这就是你的 table 的样子,

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;
     }
 }

希望对您有所帮助!

如果你不想使用循环,试试这个...

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>();
 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 , "")
}