HOW TO:建立巢狀群組 (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 迴圈來反覆查看巢狀群組的內部項目。
編譯程式碼
這個範例內含在 HOW TO:查詢物件集合 (C# 程式設計手冊) 中的範例應用程式中所定義的物件之參考。 若要編譯和執行這個方法,請將方法貼上至該應用程式中的 StudentClass 類別,並加入來自 Main 方法的呼叫。
在配合應用程式調整這個方法時,請注意,LINQ 需要 3.5 版的 .NET Framework,而且專案必須包含 System.Core.dll 的參考,以及 System.Linq 的 using 指示詞。 LINQ to SQL、LINQ to XML 和 LINQ to DataSet 型別需要額外的 Using 和參考。 如需詳細資訊,請參閱 HOW TO:建立 LINQ 專案。