GroupBy and Sum
Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 12 of 20.
GroupBy sorts items into groups that share a key. Each group has that Key and is itself a collection, so the other LINQ methods work on it. Sum, Count, Average, Min and Max reduce a collection to one number:
var sales = new List<Sale> { new("Ana", 20m), new("Ben", 5m), new("Ana", 7m) };
foreach (var g in sales.GroupBy(s => s.Customer))
{
Console.WriteLine($"{g.Key}: {g.Sum(s => s.Total)} ({g.Count()})");
}This prints Ana: 27 (2) and Ben: 5 (1). Groups come out in the order their first item appears. Sum of an empty collection is 0, while Max and Average throw on one.
Challenge
EasyAdd a categories command that shows where the money goes.
- Add
case "categories":abovedefault:. - Group the expenses by
Category, and sort the groups by the sum of their amounts, biggest first. - For each group print the category, its total with two decimals, and how many expenses it has in parentheses. With the three expenses in
expenses.json,dotnet run -- categoriesprints:food: 44.30 (2) travel: 4.20 (1)
Try it: the terminal beside the editor already reads dotnet run -- categories, so press Run: the two lines above. Raise Train's amount in expenses.json to 50 and Run again: travel: 50.00 (1) moves to the top.
Try it yourself
using System.Globalization;
using System.Text.Json;
var file = "expenses.json";
var expenses = new List<Expense>();
if (File.Exists(file))
{
expenses = JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(file)) ?? new List<Expense>();
}
var count = expenses.Count;
var total = expenses.Sum(e => e.Amount);
if (args.Length == 0)
{
Console.WriteLine("Expense Tracker");
Console.WriteLine($"{count} expenses");
Console.WriteLine($"Total: {total:F2}");
}
else
{
switch (args[0])
{
case "add":
if (args.Length < 3)
{
Console.Error.WriteLine("Usage: add <name> <amount> [category]");
return 1;
}
if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
{
Console.Error.WriteLine($"Invalid amount: {args[2]}");
return 1;
}
var category = args.Length > 3 ? args[3] : "other";
var expense = new Expense(args[1], amount, category);
expenses.Add(expense);
File.WriteAllText(file, JsonSerializer.Serialize(expenses));
Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
break;
case "remove":
if (args.Length < 2)
{
Console.Error.WriteLine("Usage: remove <name>");
return 1;
}
Expense? match = expenses.Find(e => e.Name == args[1]);
if (match is null)
{
Console.Error.WriteLine($"No expense named {args[1]}.");
return 1;
}
expenses.Remove(match);
File.WriteAllText(file, JsonSerializer.Serialize(expenses));
Console.WriteLine($"Removed {match.Name}: {match.Amount:F2}");
break;
case "list":
var shown = args.Length > 1 ? expenses.Where(e => e.Category == args[1]).ToList() : expenses;
if (shown.Count == 0)
{
Console.WriteLine("No expenses.");
break;
}
foreach (var line in shown.Select(e => $"{e.Name}: {e.Amount:F2} ({e.Category})"))
{
Console.WriteLine(line);
}
break;
case "top":
var howMany = 3;
if (args.Length > 1 && !int.TryParse(args[1], out howMany))
{
Console.Error.WriteLine($"Invalid number: {args[1]}");
return 1;
}
var biggest = expenses.OrderByDescending(e => e.Amount).Take(howMany);
foreach (var line in biggest.Select((e, i) => $"{i + 1}. {e.Name}: {e.Amount:F2} ({e.Category})"))
{
Console.WriteLine(line);
}
break;
default:
Console.Error.WriteLine($"Unknown command: {args[0]}");
return 1;
}
}
return 0;
This lesson includes a short quiz. Start the lesson to answer it and track your progress.