GroupBy

Grouping by a single property

Grouping by a single property is the simplest of all groupings. GroupBy method is used to create a group object. Every group object has the Key property. The following example groups customers by Country and the selects this Country as a single type result using the Select method:

List<string> countries =
    context.Customers
        .GroupBy(c => c.Country)
        .Select(g => g.Key)
        .ToList();

Grouping by multiple properties

To group by multiple properties, use an anonymous object. The whole object it then considered the Key. This example groups customers by Country and City:

var customers =
    context.Customers
        .GroupBy(c => new
        {
            Country = c.Country,
            City = c.City
        })
        .Select(g => new
        {
            Country = g.Key.Country,
            City = g.Key.City
        })
        .ToList();

Using aggregates

Apart from selecting the Key properties, you can also include various aggregates in the result. To get the number of customers from the same country and city, use the following:

var customers =
    context.Customers
        .GroupBy(c => new
        {
            Country = c.Country,
            City = c.City
        })
        .Select(g => new
        {
            Country = g.Key.Country,
            City = g.Key.City,
            Count = g.Count()
        })
        .ToList();

Should you have any questions or found a mistake that needs correcting, feel free to send an email to: info [at] linqtutorial [dot] info


Advertisements :