2008-12-05 78 views
4

正如我們所知道的,使用數據表的計算功能,我們可以得到列的總和。 但我想獲得一行數據表的總和。我會用一個例子來解釋:Datatable的行計算功能

我有一個數據表如下圖:使用計算功能,我們可以得到每列(產品)的總和。如對於產品1,2 + 12 + 50 + 13 = 77。

我想獲得公司1的總和:2 + 6 + 4 + 3 + 5 = 20

http://img123.imageshack.us/img123/1517/61519307xx5.jpg

我怎樣才能用asp.net 1.1來做到這一點?

+0

哇,你真的是在石頭的年齡做什麼! ;-) – 2008-12-05 16:03:28

回答

2

LINQ救援:

DataTable dt = WhateverCreatesDataTable(); 
DataRow dr = dt.Rows[0]; 
int sum = dt.Columns.Cast<DataColumn>().Sum(dc=>(int)dr[dc]); 

對於那些仍然在石器時代(又名pre.Net 3.5和LINQ)拖動指關節的人:

DataTable dt = WhateverCreatesDataTable(); 
DataRow dr = dt.Rows[0]; 
int sum = 0; 

foreach(DataColumn dc in dt.Columns) 
    sum += (int)dr[dc]; 
+0

我沒有使用asp.net 3.5 – mavera 2008-12-05 15:54:50

2

msdn

如果你必須在 兩個或多個列執行操作,您應該創建 一個DataColumn,其表達 屬性設置爲一個適當的表達, 和使用上的聚集表達式產生的列爲 。在這種情況下,由於 名稱爲 「總」, 和Expression屬性設置爲 這一個DataColumn:

"Quantity * UnitPrice"

2

既然你想在1.1解決這一這裏是你可以作爲一個簡單的解決方案

DataColumn totalColumn = new DataColumn(); 
totalColumn.DataType = System.Type.GetType("System.Int32"); 
totalColumn.ColumnName = "Total"; 
totalColumn.Expression = "Product1 + Product2 + Product3 + Product4 + Product5"; 

// Populate and get the DataTable dt then add this computed column to this table 

dt.Columns.Add(totalColumn); 
//Now if you access the column "Total" of the table you will get the desired result.