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

时间:2013-09-24 18:21:25

标签: c# linq lambda

有可能吗?例如,如何使用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);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

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 with lot of nested List

答案 1 :(得分:2)

我认为你的意思是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))); 

答案 2 :(得分:1)

发布这个问题为时已晚,但由于没有回复,我在这里留下了一个帖子,让那些在这里寻找类似问题的人离开。我有同样的问题将类似的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);

查看有助于找出解决方案的原始post