简体   繁体   English

C# Linq 具有两个以上嵌套级别

[英]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.到目前为止,我了解它是如何工作的,但在我的情况下,我需要添加一个额外的分组,让我们假设 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.它可能看起来有点冗长,但它很清晰,易于扩展,并且不需要分组键的尴尬和容易出错的重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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