Drill

ProblemsC# › orders

Total a basket that came off a queue

easyordersArraysMathC#

Order lines arrive from a message queue and the payload is not always clean: a line can be missing entirely, and quantities have been seen at zero.

OrderTotal(lines: list<Line?>) → 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 int OrderTotal(List<Line> lines) {
    
}

Worked examples

CallResult
OrderTotal(new List<Line> { new Line("A", 2, 100), new Line("B", 3, 50) })350
OrderTotal(new List<Line> { new Line("A", 1, 10), null, new Line("C", 2, 5) })20
OrderTotal(new List<Line> { new Line("A", 0, 999), new Line("B", -1, 999) })0
OrderTotal(new List<Line> { })0

Hint

Guard inside the loop, not before it. One bad line should not cost you the rest.

Reference solution in C#
public int OrderTotal(List<Line> lines) {
    int total = 0;
    foreach (var l in lines) {
        if (l == null || l.Qty <= 0) continue;
        total += l.Qty * l.UnitPrice;
    }
    return total;
}

The same problem in another language

More orders problems in C#