A shop's front page often shows a menu of its categories. The shop keeps no list of them: each product only knows its own category. So your API builds the list from the products, every time someone asks.
The list must be distinct: two products are in "office", but the menu shows it once. Before adding a value to a list, Contains tells you whether the list already holds it, and ! turns the answer around. Then Order() puts a list of strings in alphabetical order, with no key function. The same idea on a list of colors:
var colors = new List<string>();
foreach (var color in new List<string> { "red", "blue", "red" }) {
if (!colors.Contains(color)) {
colors.Add(color);
}
}
Console.WriteLine(string.Join(", ", colors.Order())); // blue, red
The list is built from the products on every request, so it always follows them. A product in a new category adds that category, and deleting the only product of a category removes it. Your code must answer these requests, in this order:
GET /categories → 200 ["home", "kitchen", "office"]
POST /products {"name": "Chair", "price": 45, "category": "furniture"} → 201 {"id": 5, "name": "Chair", …}
POST /products {"name": "Stapler", "price": 9, "category": "office"} → 201 {"id": 6, "name": "Stapler", …}
GET /categories → 200 ["furniture", "home", "kitchen", "office"]
DELETE /products/3 → 204
GET /categories → 200 ["furniture", "kitchen", "office"]
Your task: add a route for GET /categories that answers the distinct categories of the products, in alphabetical order, as a JSON list.
Assignment
Follow the Coding Tutorial to build the GET /categories route: an empty list, a loop over products, a Contains check, and an ordered answer.
Hint
Add a category only when the list doesn't Contains it yet. A list of strings needs no key function: Order() puts it in alphabetical order.
Free plan: 30 tutor messages. PRO is unlimited.
