2012-12-21 15 views
7

Ich versuche, Aggregat Werte aus Datentabelle zu bekommen. Aber kann nicht herausfinden, wie. Ich habe einige Beispiele in C# gesehen, konnte diese aber nicht auf vb.net übersetzen.Datatable Gruppe von mit Linq in vb.net

Ich habe Datentabelle

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 

Ich brauche ein Ergebnis zu erhalten:

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

ich Schleife nicht wollen, und die Werte manuell kombinieren. Bitte helfen Sie

Antwort

9

Sie möchten Group by Month? Sie können Sum verwenden, um die Gruppen zusammenzufassen:

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 

Dies ist eine Mischung aus Linq Abfrage- und Methoden Syntax.

+0

Vielen Dank. Das Snippet verursachte eine Casting-Ausnahme. Aber sobald ich von "Of Int32" zu "Of Decimal" gewechselt habe, hat alles als Charme funktioniert. – Nick

+0

Danke dafür, ich habe schon ewig mit einem ähnlichen Problem gerungen – majjam