LINQ-在vb中创建一个嵌套组



我正试图在visual basic LINQ查询表达式中创建嵌套组,如C#中所示:https://learn.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)"

C#代码的Visual Basic等价物是什么?

多亏了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)))

但至少它有效!

最新更新