Dane O'Connor Dane O'Connor - 3 months ago 8
C# Question

How do I group in memory lists?

I have a list of

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

aku aku
Answer

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