Tuesday 31 May 2011

Grouping with LinQ

Using LinQ to group a set of data by something is quite straightforward.

In the example below I am returning a list of bookings, which is very flat. I wanted to group the data returned by the BookingID

Using group on BookingID, I am able to rearrange the data to "group" sets of data that relate to a specific booking. Brilliant!

var bkgs = dal.GetBookings();

var distinctbkgs = (from x in bkgs
group x by x.BookingID into xx
select new
{
Booking = xx.First(),
RelatedBookings = xx.ToList()
}).ToList();