以下示例演示如何在 LINQ 查询表达式中创建嵌套组。 首先根据学生年级创建每个组,然后根据每个人的姓名进一步细分为小组。
public void QueryNestedGroups()
{
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; // Three nested foreach loops are required to iterate
// over all elements of a grouped group. Hover the mouse
// cursor over the iteration variables to see their actual type.
foreach (var outerGroup in queryNestedGroups)
{
Console.WriteLine($"DataClass.Student Level = {outerGroup.Key}");
foreach (var innerGroup in outerGroup)
{
Console.WriteLine($"\tNames that begin with: {innerGroup.Key}");
foreach (var innerGroupElement in innerGroup)
{
Console.WriteLine("\t\t{innerGroupElement.LastName} {innerGroupElement.FirstName}");
}
}
}
}
请注意,需要使用 3 个嵌套的 foreach
循环来循环访问嵌套组的内部元素。