user1590636
user1590636

Reputation: 1194

VB.NET LINQ Join 2 tables , then group by a column then sum

Datatable1

Name   Quantity
A       2
B       5
C       3
D       4

Datatable2

  Name   Quantity
    A       1
    B       3
    F       4
    G       4

Expected Result After Joining Both Datatables Grouping By Name Then Sum Quantity for each group putting the result in a new datatable

 Name   Quantity
    A       3
    B       8
    C       3
    D       4
    F       4
    G       4

is it possible to this using LINQ? note that i access a field value as row.Field(of T)("Name")

Upvotes: 0

Views: 2526

Answers (1)

Mitul
Mitul

Reputation: 9854

Try this. I think you need Union if both the tables are the same

Dim query = From x in ((From p in DataTable1
                Select p).Union(From pd in DataTable2 Select pd))
                Group x By Key = x.Name Into grouping = Group
                let myProdSum = grouping.Sum(Function(x) => x.Quantity)
                Select New With {.Name = grouping.Key, .TotalQty = myProdSum}

ForEach s in query 
  Console.WriteLine("{0} : {1}" , s.Name, s.TotalQty)
Next

Upvotes: 1

Related Questions