簡體   English   中英

C# Linq 具有兩個以上嵌套級別

[英]C# Linq with more than two nested levels

我見過幾個嵌套組的例子,例如學生首先按年分組,然后按姓氏分組:

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;

然后他們遍歷循環以提取值

 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}");
        }
    }
}

到目前為止,我了解它是如何工作的,但在我的情況下,我需要添加一個額外的分組,讓我們假設 FirstName。 我嘗試過類似下面的方法,但無濟於事。 有人可以建議嗎?

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)
from newGroup3 in
(from student in newGroup2
 group student by student.FirstName)
group newGroup3 by newGroup2.Key;

我還嘗試將第三個嵌套組放在第二個嵌套組中,但是我什至無法構建項目。 任何幫助將非常感激。

我寧願使用匿名類型的嵌套:

from student in students
group student by student.Year into g1
select new
{
    Year = g1.Key,
    Students =
        from student in g1
        group student by student.LastName into g2
        select new
        {
            LastName = g2.Key,
            Students =
                from student in g2
                group student by student.FirstName into g3
                select new
                {
                    FirstName = g3.Key,
                    Students = g3
                }
        }
}

它可能看起來有點冗長,但它很清晰,易於擴展,並且不需要分組鍵的尷尬和容易出錯的重復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM