2012-12-21 29 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