Summarize records with LINQ grouping
C#
using System;
using System.Linq;
// Immutable row type: records give value equality and easy printing.
public record Order(string Region, int Quantity, decimal Price);
/// <summary>Groups orders by region and prints a compact revenue report.</summary>
public static class OrderReport
{
public static void Main()
{
Order[] orders =
{
new("North", 2, 9.99m),
new("South", 5, 4.50m),
new("North", 1, 19.00m),
new("South", 3, 7.25m),
};
var report = orders
.Where(o => o.Quantity > 0)
.GroupBy(o => o.Region)
.Select(g => new
{
Region = g.Key,
Orders = g.Count(),
Units = g.Sum(o => o.Quantity),
Revenue = g.Sum(o => o.Quantity * o.Price)
})
.OrderByDescending(row => row.Revenue);
foreach (var row in report)
{
Console.WriteLine($"{row.Region,-8} {row.Orders,3} orders, revenue {row.Revenue:C}");
}
}
}