How do I group in memory lists?

2019-06-24 04:52发布

I have a list of Foo. Foo has properties Bar and Lum. Some Foos have identical values for Bar. How can I use lambda/linq to group my Foos by Bar so I can iterate over each grouping's Lums?

2条回答
看我几分像从前
2楼-- · 2019-06-24 05:19
var q = from x in list
        group x by x.Bar into g
        select g;

foreach (var group in q)
{
    Console.WriteLine("Group " + group.Key);
    foreach (var item in group)
    {
        Console.WriteLine(item.Bar);
    }
}
查看更多
相关推荐>>
3楼-- · 2019-06-24 05:20

Deeno,

Enjoy:

var foos = new List<Foo> {
   new Foo{Bar = 1,Lum = 1},
   new Foo{Bar = 1,Lum = 2},
   new Foo{Bar = 2,Lum = 3},
};

// Using language integrated queries:

var q = from foo in foos
        group foo by foo.Bar into groupedFoos
        let lums = from fooGroup in groupedFoos
                   select fooGroup.Lum
        select new { Bar = groupedFoos.Key, Lums = lums };

// Using lambdas

var q = foos.GroupBy(x => x.Bar).
            Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});


foreach (var group in q)
{
    Console.WriteLine("Lums for Bar#" + group.Bar);
    foreach (var lum in group.Lums)
    {
        Console.WriteLine(lum);
    }
}

To learn more about LINQ read 101 LINQ Samples

查看更多
登录 后发表回答