2013-10-18 35 views
0

我有表如下圖所示:如何計算特定列值的總和?

col1  col2 
1   20 

2   40 

3   60 

我要輸出表像下一個:

col1  col2 
1   20 

2   40 

3   60 

total 120 

我使用下面的代碼,但它不工作。

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

在此先感謝。

+0

你是怎麼在C#中使用? WinForms? DataGrid?我對你有很多問題,但你必須提供一些解釋。不要讓我們猜測。 –

+0

上午使用winforms數據表使用c# –

+0

'col2'的類型是什麼? –

回答

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

試試這個 -

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

@andy錯了嗎? –

+0

@andy從未見過RAMARAJ.M提到優化。 – Tafari

+0

@andy我接受這是一個古老的方法,但它仍然是一個正確的答案。這對初學者也很有幫助。通過放置-1你會傷害所有人。 –