Path: redb/redb.Examples/Examples/E128_GroupBySimple.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E128_GroupBySimple.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Groups objects by a field and calculates aggregates per group. /// SQL: GROUP BY Department with SUM, AVG, COUNT, plus AVG over a field two nested classes deep /// (HomeAddress.Building.Floor). /// [ExampleMeta("E128", "GroupBy - Simple", "Analytics", ExampleTier.Free, 128, "GroupBy", "Aggregation", "Analytics", RelatedApis = ["IRedbQueryable.GroupBy", "IGroupedQueryable.SelectAsync"])] public class E128_GroupBySimple : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Uncomment to see generated SQL: // var sql = await redb.Query() // .GroupBy(x => x.Department) // .ToSqlStringAsync(g => new { Dept = g.Key, Total = Agg.Sum(g, x => x.Salary) }); // Console.WriteLine(sql); var byDept = await redb.Query() .GroupBy(x => x.Department) .SelectAsync(g => new { Department = g.Key, TotalSalary = Agg.Sum(g, x => x.Salary), AvgAge = Agg.Average(g, x => x.Age), AvgFloor = Agg.Average(g, x => x.HomeAddress!.Building!.Floor), Count = Agg.Count(g) }); sw.Stop(); var first = byDept.FirstOrDefault(); return Ok("E128", "GroupBy - Simple", ExampleTier.Free, sw.ElapsedMilliseconds, byDept.Count, [$"Groups: {byDept.Count}", $"First: {first?.Department ?? "N/A"}, Count: {first?.Count ?? 0}, Avg home floor: {first?.AvgFloor:F2}"]); } }