如何通过 lambda/method表达式使用 linq 创建嵌套组

本文关键字:linq 创建 嵌套 表达式 何通过 lambda method | 更新日期: 2023-09-27 18:32:42

可能吗?例如,您将如何使用 lambda 表达式重写下面的工作代码?

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

如何通过 lambda/method表达式使用 linq 创建嵌套组

我想你的意思是method syntax

var queryNestedGroups = students.GroupBy(x=>x.Year, (key,g1)=>
                              g1.GroupBy(x=>x.LastName, (key2,g2)=>
                              g2.GroupBy(x=>x.Year)));//Because the group1.Key is exactly Year;

如果您不想硬编码地使用Year。试试这个:

var queryNestedGroups = students.GroupBy(x=>x.Year, (key,g1)=> 
                        g1.Select(x=>new{key,x})
                          .GroupBy(x=>x.x.LastName, (key2,g2)=>
                        g2.GroupBy(x=>x.key, x=>x.x))); 
var names = myClass1List
    .SelectMany(c1 => c1.Class2List.Where(c2 => c2.Name == "something"))
    .SelectMany(c2 => c2.Class3List.Select(c3 => c3.Name));
var names = myClass1List
    .SelectMany(c1 => c1.Class2List
        .Where(c2 => c2.Name == "something")
        .SelectMany(c2 => c2.Class3List
            .Select(c3 => c3.Name)));

另请参阅: LINQ on List 包含大量嵌套列表

现在发布这个问题为时已晚,但由于没有发布答案,我将在这里为那些登陆这里寻求类似问题的人留下一篇文章。我在将类似的 linq 查询转换为 lambda 表达式时遇到了同样的问题。

以下是您可以做到这一点的方法:

var res1 = students.GroupBy(th=>th.Year)
                           .SelectMany (grp1 => grp1.GroupBy (th => th.LastName), (grp1, grp2) => new {grp1 = grp1, grp2 = grp2})
                           .GroupBy (temp0 => temp0.grp1.Key, temp0 => temp0.grp2);

请参阅有助于找出解决方案的原始帖子。