BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

LINQ
.NET 3.5+

LINQ Grouped Joins

The ninth part of the LINQ to Objects tutorial looks at grouped joins. These allow two collections to be combined in a join operation based upon matching key values. The results are then grouped into keyed collections that may be aggregated.

Grouped Joins with Query Expression Syntax

In this section of the article we will recreate the previous examples using query expression syntax. To perform a group join in a query, the join clause is used to join the two lists and into clause is used to store the results in a temporary variable. You can then project the results using the select clause.

The following code recreates the first example, which created a list of categories that each contained a selection of stock items:

var joined =
    from c in categories
    join s in stock on c.Name equals s.Category into stockItems
    select new
    {
        MinorCategory = c.Name,
        MajorCategory = c.MajorCategory,
        StockItems = stockItems
    };

/* RESULTS

Chilled/Dairy
    Milk/1.12
Fresh/Fruit
    Apple/0.3
    Banana/0.35
    Orange/0.29
Fresh/Vegetable
    Cabbage/0.49
    Carrot/0.29
    Lettuce/0.3
    
*/

The same process can be used with aggregate operators in the projection clause. The following sample recreates the second example, which created a list of categories containing major and minor category names and the count and total price of the contained stock items:

var joined =
    from c in categories
    join s in stock on c.Name equals s.Category into stockItems
    select new
    {
        MinorCategory = c.Name,
        MajorCategory = c.MajorCategory,
        NumberOfItems = stockItems.Count(),
        TotalPrice = stockItems.Sum(s => s.Price)
    };

/* RESULTS

Chilled/Dairy/1/1.12
Fresh/Fruit/3/0.94
Fresh/Vegetable/3/1.08

*/
2 September 2010