EF Core by Myles

Grouping by multiple columns in EF Core

The provided code snippet demonstrates a LINQ query to group by multiple columns while also finding the maximum item ID within each group. Here's a breakdown of the code:

var result = from o in context.Orders
             group o by new { o.CustomerId, o.OrderType } into g
             select new
                 CustomerId = g.Key.CustomerId,
                 OrderType = g.Key.OrderType,
                 MaxItemId = g.Max(x => x.ItemId)

In this code:

  • The group by new { o.CustomerId, o.OrderType } syntax allows grouping by a combination of CustomerId and OrderType using an anonymous type
  • The into g clause signifies that the grouped data will be accessible through the identifier g
  • The g.Key property allows access to the grouped key values, such as CustomerId and OrderType.
  • select new { ... } creates a new anonymous object for each group containing CustomerId, OrderType, and the maximum ItemId
  • The Max() method is used to find the maximum ItemId within each group (g.Max(x => x.ItemId))

This code efficiently retrieves the maximum ItemId for each unique combination of CustomerId and OrderType in the orders collection.


Leave a Comment

All fields are required. Your email address will not be published.