VB Linq双分组错误

时间:2013-01-09 21:38:17

标签: .net vb.net linq

我的VB代码中有一个Datatable,我希望在两个级别中分组(换句话说,在另一个组中分组),我遇到了问题。

为了便于说明,假设我的数据表MyTable具有如下列:

Name1     Name2    Start_Date    End_Date   Var1    Var2

所以,假设我想把它分组,比如Name1,我可以这样做:

Dim Query1 = From dr as DataRow in MyTable
             Group dr by Name1 = dr.Item("Name1") into Group

然后我可以循环遍历该组中的所有记录:

For Each Grp in Query1
   For Each dr as DataRow in Grp.Rows
      ... do whatever ...
   Next
Next

现在,我想创建一个双组 - 例如,假设我想创建一个内存查询,首先按Start_DateEnd_Date进行分组,然后在WITHIN THAT GROUP中创建一个第二次分组Name1所以我可以写一个循环:

For Each MainGrp in BiggerQuery
   For Each SubGrp in MainGrp
        For Each dr as DataRow in SubGrp .Rows
            ... do whatever ...
        Next
   Next
Next

如何在VB中对Linq查询进行双重分组? - 我的第一个问题是,VB似乎要求你命名你的组Group,这不允许进行双重分组,其次,我似乎无法找出整个查询。

感谢!!!

1 个答案:

答案 0 :(得分:1)

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)

我认为它应该有效,但现在无法测试。

修改

在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)