Reputation: 19574
I have a Datatable in my VB code that I want to group in two levels (In other words group within another group) and I'm having a problem doing it.
For illustration's sake, suppose my datatable, MyTable
, had columns as follows:
Name1 Name2 Start_Date End_Date Var1 Var2
So, supposing I wanted to just group it by, say, Name1
, I could do it as follows:
Dim Query1 = From dr as DataRow in MyTable
Group dr by Name1 = dr.Item("Name1") into Group
And then I could loop through all the records in that group doing something along the lines of:
For Each Grp in Query1
For Each dr as DataRow in Grp.Rows
... do whatever ...
Next
Next
Now, I would like to create a double group - For Example, suppose I wanted to create an in-memory query that first groups by Start_Date
and End_Date
and then, WITHIN THAT GROUP, a second grouping by Name1
so I could write a loop along the lines of:
For Each MainGrp in BiggerQuery
For Each SubGrp in MainGrp
For Each dr as DataRow in SubGrp .Rows
... do whatever ...
Next
Next
Next
How would that double-grouped Linq query look in VB? - My first issue is that it seems that VB requires you to name your group Group
, which doesn't allow for double-grouping and secondly, I can't seem to figure out the query as a whole.
Thanks!!!
Upvotes: 0
Views: 575
Reputation: 125650
Dim query = From dr1 As DataRow In MyTable
Group dr1 By New With { .StartDate = dr1.StartDate, .EndDate = dr1.EndDate } Into g1 = Group
Select newGroup = (From dr2 As DataRow In g1
Group dr2 By dr2.Name1 Into g2 = Group
Select g2)
I think it should work, but cannot test it right now.
EDIT
There is a nice example of nested grouping on MSDN: http://msdn.microsoft.com/en-us/vstudio/bb737908#grpbynest
EDIT2
From dr1 As DataRow In myTable
Group dr1 By gi1 = New With {.StartDate = dr1.Item("StartDate"), .EndDate = dr1.Item("EndDate")} Into g1 = Group
Select newGroup = (From dr2 As DataRow In g1
Group dr2 By gi2 = dr2.Item("Name1") Into g2 = Group
Select g2)
Upvotes: 1