Start learning free

LESSON 18 OF 173 · BACKEND: YOUR FIRST API

Filter with a Query String in C#

Practice

A client often wants only part of the data, and it can say so in the URL. Everything after the ? is the query string, made of name=value pairs. In /products?max_price=10 the path is still /products, so the same route answers: max_price is the name and 10 is the value.

In ASP.NET Core you read a query parameter by giving the route's lambda a parameter with the same name, like string? max_price. Everything in a URL is text, and the parameter is null when the URL leaves it out. int.TryParse(text, out var n) gives true and puts the whole number in n, or gives false when the text is missing or isn't a whole number. Here is the idea on another route:

app.MapGet("/double", (string? number) => {
    if (!int.TryParse(number, out var n)) {
        return "Send a whole number, like /double?number=4";
    }
    return (n * 2).ToString();
});

The filter is a loop you already know: start an empty list, go through the products, and Add the ones that pass the check. The prices sit in the dictionaries as object, so write (int) before one to compare it. When there is no max_price, every product passes, so /products still answers the whole list. Your code must give:

GET /products?max_price=10     →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?max_price=12     →  200  [{"id": 1, "name": "Mug", …}, {"id": 2, …}, {"id": 4, …}]
GET /products?max_price=1      →  200  []
GET /products                  →  200  all 4 products
GET /products?max_price=cheap  →  200  all 4 products
GET /products/3                →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home"}

Your task: in the /products route, whose first line with string? max_price is already in your file, turn max_price into a number with int.TryParse and answer only the products that cost that much or less, or every product when there is no limit.


Assignment
Follow the Coding Tutorial to read max_price and filter the list in the /products route.


Hint
Check !hasMax first, then ||, then compare (int)product["price"] with <=. Return result after the loop, not inside it.


STEP 1 OF 6
    Ctrl + Enter to check

    Shop Max Price in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free