LINQ-在vb中创建嵌套组

时间:2018-11-08 10:59:45

标签: vb.net linq

我正在尝试在可视的基本LINQ查询表达式中创建嵌套组,如C#中所示:https://docs.microsoft.com/en-us/dotnet/csharp/linq/create-a-nested-group

    var queryNestedGroups =
    from student in students
    group student by student.Year into newGroup1
    from newGroup2 in
        (from student in newGroup1
         group student by student.LastName)
    group newGroup2 by newGroup1.Key;

这是我到目前为止所拥有的:

    Dim students As New List(Of Student)
    '...getting students content ommitted here...
    Dim queryNestedGroups As IEnumerable(Of IGrouping(Of Integer, IGrouping(Of String, Student))) =
            From student In students
            Group student By student.Year Into newGroup1 = Group
            From newGroup2 In (From student In newGroup1 Group student By student.LastName Into Group)
            Group newGroup2 By newGroup1.Key Into Group
'                              ^^^^^^^^^^^^^ compiler red lines here

    Dim grouping As IGrouping(Of Integer, IGrouping(Of String, Student))
    For Each grouping In queryNestedGroups
        Console.WriteLine($"DataClass.Student Level = {grouping.Key}")
        Dim grouping2 As IGrouping(Of String, Student)
        For Each grouping2 In grouping
            Console.WriteLine((ChrW(9) & "Names that begin with: " & grouping2.Key))
            Dim student As Student
            For Each student In grouping2
                Console.WriteLine((ChrW(9) & ChrW(9) & student.LastName & " " & student.FirstName))
            Next
        Next
    Next

但是编译器抱怨 newGroup1.Key

"Key" is not a member of "IEnumerable(Of Student)"

Visual Basic与C#代码等效吗?

1 个答案:

答案 0 :(得分:1)

感谢Jimi,这将产生与C#代码相同的结果:

    Dim queryNestedGroups =
            From student In students
            Group student By student.Year Into newGroup1 = Group
            From newGroup2 In (From student In newGroup1 Group student By LastName = student.LastName Into Group)
            Group newGroup2 By Year Into Group

    For Each grouping In queryNestedGroups
        Console.WriteLine($"DataClass.Student Level = {grouping.Year}")
        For Each grouping2 In grouping.Group
            Console.WriteLine((ChrW(9) & "Names that begin with: " & grouping2.LastName))
            Dim student As Student
            For Each student In grouping2.Group
                Console.WriteLine((ChrW(9) & ChrW(9) & student.LastName & " " & student.FirstName))
            Next
        Next
    Next

作为缺点,结果 queryNestedGroups 现在是匿名类型,没有

IEnumerable(Of IGrouping(Of Integer, IGrouping(Of String, Student)))

但至少可以正常工作!