tags:

views:

184

answers:

2

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  A: 
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);
    }
}
aku
+3  A: 

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

aku