Order the results of a join clause

This example shows how to order the results of a join operation. Note that the ordering is performed after the join. Although you can use an orderby clause with one or more of the source sequences before the join, generally we do not recommend it. Some LINQ providers might not preserve that ordering after the join.

Note

The example in this topic uses the following data classes:

record Product(string Name, int CategoryID);
record Category(string Name, int ID);

Example

This query creates a group join, and then sorts the groups based on the category element, which is still in scope. Inside the anonymous type initializer, a sub-query orders all the matching elements from the products sequence.

List<Category> categories = new()
{
    new(Name: "Beverages", ID: 001),
    new("Condiments", 002),
    new("Vegetables", 003),
    new("Grains", 004),
    new("Fruit", 005)
};

List<Product> products = new()
{
    new(Name: "Cola", CategoryID: 001),
    new("Tea", 001),
    new("Mustard", 002),
    new("Pickles", 002),
    new("Carrots", 003),
    new("Bok Choy", 003),
    new("Peaches", 005),
    new("Melons", 005),
};

var groupJoinQuery2 =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID into prodGroup
    orderby category.Name
    select new
    {
        Category = category.Name,
        Products =
            from prod2 in prodGroup
            orderby prod2.Name
            select prod2
    };

foreach (var productGroup in groupJoinQuery2)
{
    Console.WriteLine(productGroup.Category);
    foreach (var prodItem in productGroup.Products)
    {
        Console.WriteLine($"  {prodItem.Name,-10} {prodItem.CategoryID}");
    }
}

/* Output:
    Beverages
      Cola       1
      Tea        1
    Condiments
      Mustard    2
      Pickles    2
    Fruit
      Melons     5
      Peaches    5
    Grains
    Vegetables
      Bok Choy   3
      Carrots    3
 */

See also