C#如何获取数据表中多列的总和

How to get the sum of multiple columns of a datatable in c#

我只想得到datatable中每个数据行的三列之和。我有一个大约有 15 列的 DT,我只想要第 7 列、第 9 列和第 10 列的总和。所有列都是字符串类型。 我尝试了几种使用 LINQ 的方法,但都失败了。

如果所有列都是字符串但实际上代表浮点数:

double totalSum = dt.AsEnumerable()
    .Sum(r=> double.Parse(r[7].ToString()) + double.Parse(r[9].ToString()) + double.Parse(r[10].ToString()));

如果有些为空或有无效数字,您需要使用 double.TryParse

这是解决方案,即使列类型是字符串,它也适用于我:

for (int i = 11; i < dt.Rows.Count; i++)
{
    for (int j = 14; j <= 18; j += 2)
    {
        if (j > 17)
            j -= 1;
        if(!string.IsNullOrEmpty(dt.Rows[i][2].ToString()))
        { 
            newdt.Rows.Add(dt.Rows[i][18], dt.Rows[i][19], 
            dt.Rows[i][j]);
        } 
    }
}
    
try
{
    var result = 0;
    if (newdt.Rows.Count != 0)
    {                          
        result = newdt.AsEnumerable().Sum(x => Convert.ToInt32(x["Column7"]));
        subdt.Rows.Add(dt.Rows[i][18], dt.Rows[i][19], result) 
    }
...