简体   繁体   中英

C# Linq with more than two nested levels

I have seen several examples of nested groups, eg Students where the students grouped first by Year and then by Surname:

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;

and then they iterate through the loops to extract the values

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

I understand how it works so far, but in my case i need to add an additional grouping, let's assume by FirstName. I have tried something like below, but to no avail. Can one advise, please?

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;

I have also tried to place the third nested group inside the second, but then I cannot even build the project. Any help would be much appreciated.

I'd rather use a nesting of anonymous types:

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
                }
        }
}

It may look a bit more verbose, but it's clear, easy to extend, and it doesn't require the awkward and error-prone repetition of grouping keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM