GroupBy splits a sequence into groups that share a key. It returns IEnumerable<IGrouping<TKey, TElement>>, where each group has a Key property and is itself a sequence of the matching elements. Basic example var orders = new[] { new Order("Asha", "Books", 500m), new Order("Ravi", "Books", 300m), new Order("Asha", "Electronics", 15000m) }; var byCustomer = orders.GroupBy(o => o.Customer); foreach (var group in byCustomer) { Console.WriteLine($"{group.Key}: {group.Count()} orders, total {group.Sum(o => o.Amount)}"); } Projecting results (very common) var summary = orders .GroupBy(o => o.Category) .Select(g => new { Category = g.Key, Count = g.Count(), Revenue = g.Sum(o => o.Amount) }) .OrderByDescending(x => x.Revenue) .ToList(); Query syntax: var summary2 = from o in orders group o by o.Category into g select new { g.Key, Total = g.Sum(x => x.Amount) }; Composite keys GroupBy(o => new { o.Customer, o.Category }) groups by several properties; anonymous types and records compare by value. Other overloads - Element selector: GroupBy(o => o.Customer, o => o.Amount) groups only the amounts. - Result selector: GroupBy(o => o.Customer, (key, items) => new { key, Total = items.Sum(i => i.Amount) }). - Custom comparer: GroupBy(o => o.Email, StringComparer.OrdinalIgnoreCase). How it works (LINQ to Objects) - Deferred execution: grouping happens when you enumerate. - On first enumeration it reads the whole source into an internal Lookup (hash table of keys to lists), so it is O(n) with memory proportional to the input. - Groups appear in the order their keys were first encountered, and elements keep their original order within each group. - ToLookup does the same immediately and lets you index by key. GroupBy with EF Core - GroupBy followed by aggregates (Count, Sum, Max) translates to SQL GROUP BY. - Returning the grouped entities themselves is supported only in limited forms or may be evaluated on the client; prefer projecting aggregates in Select. .NET 9 added CountBy and AggregateBy, simpler alternatives when you only need counts or aggregates per key.
Ravindra Wadile · · 0 likes