Menu
CoddyTech

Dictionaries

Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 13 of 20.

A Dictionary<TKey, TValue> stores values under unique keys and finds one by its key quickly, however many it holds. Writing to a key adds it or replaces its value. Reading a missing key with [...] throws a KeyNotFoundException, so ask with TryGetValue when the key may be missing:

var stock = new Dictionary<string, int> { ["apples"] = 4 };
stock["pears"] = 7;
if (stock.TryGetValue("kiwis", out var kiwis))
    Console.WriteLine($"{kiwis} kiwis");
else
    Console.WriteLine("No kiwis");
foreach (var (fruit, count) in stock)
    Console.WriteLine($"{fruit}: {count}");

A JSON object such as { "apples": 4 } deserializes into a Dictionary<string, int>. Do not rely on the order of a dictionary's items; sort them when order matters.

challenge icon

Challenge

Easy

Your project now has budgets.json, a spending limit per category. Warn when an expense takes its category over the limit.

  1. Above var count, declare var budgets = new Dictionary<string, decimal>(); and, when budgets.json exists, load it the way you load expenses.json.
  2. In the add case, after the Added line, look up the category with budgets.TryGetValue. A category with no budget prints nothing more.
  3. When it has a budget, add up the amounts of all expenses in that category, the new one included. When the sum is over the budget, print:
    Over budget for food: 54.20 of 50.00

Try it: the terminal beside the editor already reads dotnet run -- add Snacks 9.90 food, so press Run: food reaches 54.20, and you see Added Snacks: 9.90 (food) and the warning above. Raise food in budgets.json to 60 and Run again: only the Added line.

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;
        case "categories":
            var groups = expenses.GroupBy(e => e.Category).OrderByDescending(g => g.Sum(e => e.Amount));
            foreach (var g in groups)
            {
                Console.WriteLine($"{g.Key}: {g.Sum(e => e.Amount):F2} ({g.Count()})");
            }
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;

All lessons in C# and .NET Basics