A real shop can have thousands of products, and a page often shows only a few. A client asks for that with a query parameter: ?limit=2 means "at most 2 products".
To keep the first few items of a list, use Take. items.Take(n) keeps the first n items, and .ToList() turns them back into a list. If n is bigger than the list, you simply get the whole list.
var days = new List<string> { "Mon", "Tue", "Wed", "Thu", "Fri" };
Console.WriteLine(string.Join(", ", days.Take(2))); // Mon, Tue
Console.WriteLine(string.Join(", ", days.Take(10))); // the whole list, no error
Cut the list last, after filtering and sorting, so ?sort=price&limit=2 gives the two cheapest products. A limit of 0 or less makes no sense, so it gets 400. Without limit, the answer is the whole list, as before. The lists below show product names only.
GET /products?limit=2 → 200 [Mug, Notebook]
GET /products?sort=price&limit=2 → 200 [Pen, Notebook]
GET /products?category=office&limit=1 → 200 [Notebook]
GET /products?limit=10 → 200 [Mug, Notebook, Lamp, Pen]
GET /products?limit=0 → 400 {"error": "Limit must be 1 or more"}
GET /products?limit=-3 → 400 {"error": "Limit must be 1 or more"}
Your task: in GET /products, read limit as a whole number, answer 400 when it is less than 1, and cut the list to its first limit products.
Assignment
Follow the Coding Tutorial to add a limit to GET /products.
Hint
The route already takes string? limit, and the max price number is now called maxPrice. Read limit with int.TryParse, like max_price. Check it before the loop, and cut result with Take just before the return, after the sorting.
Free plan: 30 tutor messages. PRO is unlimited.
