Interview question
Group orders by customer summary
Builds customer summaries from order rows using grouping, aggregation, and deterministic ordering.
TL;DR
Builds customer summaries from order rows using grouping, aggregation, and deterministic ordering.
Grouping, aggregation, decimal handling, ordering, DTO shaping, and readable C#.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement SummarizeOrders(IEnumerable<Order> orders) returning one CustomerSummary per customer. Each summary includes customer id, order count, and total amount. Output is ordered by total amount descending, then customer id ascending.
Next in Coding Practice: Dedupe Events
Input rows: (C1, 10.00), (C2, 7.50), (C1, 5.00)
Output: C1 -> count 2, total 15.00; C2 -> count 1, total 7.50
decimal for money-like totals.I would group by customer id, then project each group into a summary with Count() and Sum(). I would call out that this is in-memory LINQ over an IEnumerable; in EF Core, I would be more careful about translation and the generated SQL. The deterministic ordering is part of the contract, not a cosmetic detail.
public sealed record Order(string CustomerId, decimal Amount);
public sealed record CustomerSummary(string CustomerId, int OrderCount, decimal TotalAmount);
public static IReadOnlyList<CustomerSummary> SummarizeOrders(IEnumerable<Order>? orders)
{
if (orders is null)
{
return Array.Empty<CustomerSummary>();
}
return orders
.Where(order => !string.IsNullOrWhiteSpace(order.CustomerId))
.GroupBy(order => order.CustomerId, StringComparer.Ordinal)
.Select(group => new CustomerSummary(
group.Key,
group.Count(),
group.Sum(order => order.Amount)))
.OrderByDescending(summary => summary.TotalAmount)
.ThenBy(summary => summary.CustomerId, StringComparer.Ordinal)
.ToList();
}
Time is O(n + k log k): one pass to group n orders, then sorting k customer summaries. Space is O(k) for the grouped summaries, plus LINQ grouping storage.
double for money-like values.Spot a weak answer, missing edge case, or clearer explanation? Send it in.