数据表 - 连续对每个单元格求和

Mat*_*att 4 c# datatable

有很多关于如何获取列中每个单元格总和的示例.我无法找到如何对一行中的每个单元格求和并将该总数添加到名为"Total"的新列中的示例.

C#DataTable有 DataTable1.Compute("SUM(["Column Name"])", "")

我想在下面做什么的例子.但是,我也希望能够排除特定列,因为它们可能不包含数字.

在此输入图像描述

编辑表格是动态的,列数可能会更改.

Tim*_*ter 5

你可以使用这个循环:

table.Columns.Add("Total", typeof(decimal));
foreach (DataRow row in table.Rows)
{
    decimal rowSum = 0;
    foreach (DataColumn col in table.Columns)
    {
        if(!row.IsNull(col))
        {
            string stringValue = row[col].ToString();
            decimal d;
            if(decimal.TryParse(stringValue, out d))
                rowSum += d;
        }
    }
    row.SetField("Total", rowSum);
}
Run Code Online (Sandbox Code Playgroud)

这适用于任何列类型.