C# LINQ GroupBy and Aggregates
Build one total for each room while distinguishing a grouped result from an original booking record.
How it works
GroupBy collects elements sharing a key under its equality policy. Aggregation computes a summary from each group. A room total has a different meaning from one booking’s count, so name the result accordingly. In-memory grouping typically retains data to form its groups; it is not a promise of constant memory for an unlimited stream. Sum also has a numeric range contract, and a robust import should bound records or use checked accumulation for its chosen total type.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
using System.Linq;
internal static class Program
{
private static void Main(string[] args)
{
var input = new[] { new Booking("Studio", 3), new Booking("Hall", 2), new Booking("Studio", 4) };
var totals = input.GroupBy(row => row.Room, StringComparer.Ordinal)
.Select(group => new { Room = group.Key, Total = group.Sum(row => row.Places) })
.OrderBy(row => row.Room, StringComparer.Ordinal);
foreach (var row in totals) Console.WriteLine($"{row.Room}: {row.Total}");
}
}
internal sealed record Booking(string Room, int Places);
Expected result
Hall: 2
Studio: 7
The repeated Studio rows contribute to one total and the final ordering makes the output deterministic. Every fixture count is valid and the bounded sum fits int. Grouping does not automatically validate duplicate booking IDs; that is a separate identity rule. Decide whether duplicate records should be merged, rejected or retained before producing a summary.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.