2012-10-14 55 views
2

我使用LINQ我要總結爲具有相同的名稱CATID,這保存到行的quanitiy下表LINQ總結一些列2倍時,其他列的值是相同的

+-------+--------+----------+ 
| catid | name | quantity | 
+-------+--------+----------+ 
|  1 | table |  10 | 
|  2 | chair |  5 | 
|  2 | chair |  10 | 
|  1 | table |  10 | 
|  2 | chair |  15 | 
|  3 | pencil |  20 | 
+-------+--------+----------+ 

已經相同的數據表

所以結果將是此表

+-------+--------+----------+ 
| catid | name | quantity | 
+-------+--------+----------+ 
|  1 | table |  20 | 
|  2 | chair |  30 | 
|  3 | pencil |  20 | 
+-------+--------+----------+ 

回答

3
var result = (from row in YourTable 
      group row by new {row.catid, row.name} 
      into grp 
        select new 
        { 
         grp.Key.catid, 
         grp.Key.name, 
         Quantity = grp.Sum(row => row.Quantity) 
        }).ToList(); 

編輯:只注意到它的VB標記。對不起。嗯,應該是這樣的:

Dim result = From row In YourTable 
    Group By Key = New With {row.catid, row.name} Into Group 
Select New With 
{ 
.Catid = Key.catid, 
.Name = Key.Name, 
.Quantity = Group.Sum(Function(x) x.quantity) 
} 
+0

你好,謝謝,以及我只能使用字段屬性訪問行像row.Field(Of Integer)(「catid」),不能得到這個工作 – user1570048

+1

您只能將LINQ應用於實現IEnumerable的集合。也就是說,你不能直接使用DataTable或DataSet。但是你可以使用AsEnumerable方法來獲取System.Data.EnumerableRowCollection 。檢查此鏈接http://msdn.microsoft.com/en-us/library/bb386910.aspx –

1

阿圖爾Udod的答案是罰款(並有額外的功能),但簡單的LINQ的答案是:

Dim result = From row In YourTable 
      Group By row.catid, row.name Into Group 
      Select catid, name, quantity = Sum(From g In group Select g.quantity) 

(未經測試)

0

在我案例馬克的答案已經以這種形式成功:

Dim result = From row In YourTable 
     Group By row.catid, row.name Into Group 
     Select catid, name, quantity = (From g In group Select g.quantity).Sum 
相關問題