mansi lohiya
mansi lohiya

Reputation: 3

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

I want to get the sum of only three columns for each data row in datable. I have a DT with approx 15 columns and I only want the sum of column 7, column 9 and column 10. And all the columns are of string type. I tried few methods using LINQ but all failed.

Upvotes: 0

Views: 2307

Answers (2)

mansi lohiya
mansi lohiya

Reputation: 3

Here is the solution, it worked for me even if the column type is of string:

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) 
    }
...

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460048

If all columns are strings but actually represent floating point numbers:

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

If some are empty or have invalid numbers you need to use double.TryParse.

Upvotes: 1

Related Questions