2

出来ますか?たとえば、次の作業コードをラムダ式でどのように書き換えますか?

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 に答える