Project · Data

Expense tracker

Track income and expenses using collections and decimal.

All C# source files below are loaded together in the playground. Files written by a run live in its virtual directory.

Program.cs

var expenses = new List<Expense>
{
    new("Food", 12.50m),
    new("Transport", 4.25m),
    new("Food", 8.00m),
    new("Books", 19.90m),
};

var byCategory = expenses
    .GroupBy(e => e.Category)
    .Select(g => (Category: g.Key, Total: g.Sum(e => e.Amount)))
    .OrderByDescending(row => row.Total);

foreach (var row in byCategory)
{
    Console.WriteLine($"{row.Category,-10}{row.Total,8:0.00}");
}

Console.WriteLine(new string('-', 18));
Console.WriteLine($"{"Total",-10}{expenses.Sum(e => e.Amount),8:0.00}");

Models/Expense.cs

public sealed record Expense(string Category, decimal Amount);

ExpenseTracker.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AssemblyName>ExpenseTracker</AssemblyName>
  </PropertyGroup>
</Project>