2

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

3 回答 3

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

于 2013-09-24T18:25:15.810 回答
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))); 
于 2013-09-24T18:25:39.053 回答
1

It's too late to post on this question but since there's no answer been posted I'm leaving a post here for those landing here seeking similar problem. I had this same problem converting similar linq query to lambda expression.

Here's how you can do it:

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

see the original post which helped figuring out the solution.

于 2016-02-13T02:43:04.873 回答