Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group in memory lists?

Tags:

c#

.net

lambda

linq

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?

like image 848
Dane O'Connor Avatar asked Sep 05 '08 16:09

Dane O'Connor


1 Answers

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);
    }
}
like image 171
aku Avatar answered Sep 23 '22 12:09

aku