LINQ - GroupBy a key and then put each grouped item into separate 'buckets'

Saxman picture Saxman · Jul 8, 2011 · Viewed 31.8k times · Source

I have a list of items as such:

public class Item
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public int ListId { get; set; }
}

1 Test1 1

2 Test2 1

3 Test3 1

4 List 2

5 List2 2

6 Testing 3

7 Testing2 3

8 Testing3 3

Is there a way for me to group by the ListId and put them into each separate buckets, i.e, ListId1 bucket will have all items with ListId == 1. The list is dynamically returned from SQL, so I don't know before hand how many ListId there will be.

Answer

Reed Copsey picture Reed Copsey · Jul 8, 2011

You can use GroupBy:

var groups = items.GroupBy(item => item.ListId);

foreach(var group in groups)
{
     Console.WriteLine("List with ID == {0}", group.Key);
     foreach(var item in group)
        Console.WriteLine("    Item: {0}", item.ItemName);
}