Drill

ProblemsC# › data

Totals per category

mediumdataHash mapsArraysC#

A ledger groups every sale under its category so each bucket shows a single sum.

SumPerCategory(sales: list<Sale>) → map<string, int>

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public Dictionary<string, int> SumPerCategory(List<Sale> sales) {
    
}

Worked examples

CallResult
SumPerCategory(new List<Sale> { new Sale("food", 10), new Sale("food", 15) })new Dictionary<string, int> { { "food", 25 } }
SumPerCategory(new List<Sale> { new Sale("a", 3), new Sale("b", 4), new Sale("a", 5) })new Dictionary<string, int> { { "a", 8 }, { "b", 4 } }
SumPerCategory(new List<Sale> { new Sale("x", 1) })new Dictionary<string, int> { { "x", 1 } }
SumPerCategory(new List<Sale> { new Sale("p", 0), new Sale("q", -2) })new Dictionary<string, int> { { "p", 0 }, { "q", -2 } }

Hint

Aggregate into a map keyed by category, adding each amount as you go.

Reference solution in C#
public Dictionary<string, int> SumPerCategory(List<Sale> sales) {
    var result = new Dictionary<string, int>();
    foreach (var s in sales) {
        if (result.ContainsKey(s.Category)) result[s.Category] += s.Amount;
        else result[s.Category] = s.Amount;
    }
    return result;
}

The same problem in another language

More data problems in C#