HOW TO:將群組包含在群組中 (C# 程式設計手冊)
更新:2007 年 11 月
在下列範例中,會示範如何在 LINQ 查詢運算式中建立巢狀群組。
範例
private static 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);
}
}
}
}
請注意,需要三個巢狀 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 專案。