Datatable group by linq on vb.net

I am trying to get aggregated values ​​from a data table. But I can’t understand how to do this. I saw several examples in C #, but could not translate them to vb.net.

I have a data table

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 

I need to get the result:

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

I do not want to cycle through the values ​​manually. Please, help

+7
source share
1 answer

Do you want Group by Month ? You can use Sum to summarize groups:

 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 

This is a mix of Linq query- and method-syntax.

+9
source

All Articles