如何:创建嵌套组(C# 编程指南)

下面的示例演示如何在 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 = {0}", outerGroup.Key);
        foreach (var innerGroup in outerGroup)
        {
            Console.WriteLine("\tNames that begin with: {0}", innerGroup.Key);
            foreach (var innerGroupElement in innerGroup)
            {
                Console.WriteLine("\t\t{0} {1}", innerGroupElement.LastName, innerGroupElement.FirstName);
            }
        }
    }
}
/*
 Output:
DataClass.Student Level = SecondYear
        Names that begin with: Adams
                Adams Terry
        Names that begin with: Garcia
                Garcia Hugo
        Names that begin with: Omelchenko
                Omelchenko Svetlana
DataClass.Student Level = ThirdYear
        Names that begin with: Fakhouri
                Fakhouri Fadi
        Names that begin with: Garcia
                Garcia Debra
        Names that begin with: Tucker
                Tucker Lance
DataClass.Student Level = FirstYear
        Names that begin with: Feng
                Feng Hanying
        Names that begin with: Mortensen
                Mortensen Sven
        Names that begin with: Tucker
                Tucker Michael
DataClass.Student Level = FourthYear
        Names that begin with: Garcia
                Garcia Cesar
        Names that begin with: O'Donnell
                O'Donnell Claire
        Names that begin with: Zabokritski
                Zabokritski Eugene        
 */

请注意,需要使用三个嵌套的 foreach 循环来循环访问嵌套组的内部元素。

编译代码

此示例包含对如何:查询对象集合(C# 编程指南)内示例应用程序中定义的对象的引用。 若要编译和运行此方法,请将它粘贴到该应用程序的 StudentClass 类中,并且在 Main 方法中添加对它的调用。

在改写此方法以适合您自己的应用程序时,请记住 LINQ 需要 .NET Framework 3.5 版,并且项目必须包含一个对 System.Core.dll 的引用和一条针对 System.Linq 的 using 指令。 LINQ to SQL、LINQ to XML 和 LINQ to DataSet 类型需要其他 using 指令和引用。 有关更多信息,请参见 如何:创建 LINQ 项目

请参见

概念

LINQ 查询表达式(C# 编程指南)