2012-12-21 27 views
7

我試圖從數據表中獲取聚合值。但無法弄清楚如何。在c#中查看了一些示例,但無法將其轉換爲vb.net。由vb.net linq在數據表組

我有數據表

Month, campaign, sales, leads, gross 
1   1    5   10  1000 
1   2    0   5   0 
2   1    2   0   300 
2   2    1   3   200 

我需要得到一個結果:

Month, sales, leads, gross 
1   5  15  1000 
2   3   3   500 

我不想循環和手動相結合的值。請幫助

回答

9

你想Group by Month?您可以使用Sum總結組:

Dim query = From row In dt 
     Group row By Month = row.Field(Of Int32)("Month") Into MonthGroup = Group 
     Select New With { 
      Key Month, 
      .Sales = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Sales")), 
      .Leads = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Leads")), 
      .Gross = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Gross")) 
     } 

For Each x In query 
    Console.WriteLine("Month:{0} {1} {2} {3}", x.Month, x.Sales, x.Leads, x.Gross) 
Next 

這是Linq的查詢 - 和方法的語法的混合物。

+0

謝謝。該片段造成了鑄造異常。但是,一旦我從「Int32」變成「十進制」,所有這些都充當了魅力。 – Nick

+0

謝謝你,我一直在摔跤類似的問題多年 – majjam