RAMARAJ.M
RAMARAJ.M

Reputation: 129

How to calculate Total for particular column value?

I have table like below:

col1     col2
 1         20 

 2         40

 3         60

I want to output table like the following one :

col1     col2
 1         20 

 2         40

 3         60

total    120

I am using the following code but it doesn't work.

 object total = dtprofit.Compute("Sum(col2)", string.Empty);

Thanks in advance.

Upvotes: 0

Views: 1397

Answers (2)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

var total = table.AsEnumerable()
                 .Sum(dr => dr["col2"] is int ? (int)dr["col2"] : 0);

Upvotes: 3

Vikash Singh
Vikash Singh

Reputation: 814

Try this -

    Int32 sum = 0;
    foreach (DataRow dr in YourDataTable.Rows)
                sum = sum + Convert.ToInt32(dr["col2"].ToString());
    MessageBox.Show(sum.ToString()); // 

Upvotes: -1

Related Questions