Start learning free

LESSON 12 OF 173 · BACKEND: HOW THE WEB WORKS

Project: A Restock Report in C#

Practice

This project puts the whole module together. The shop wants a restock report: every product the supplier has fewer than 10 of, with its stock and its price, sorted by name. No single answer has all of that. /prices has the names and prices, and /stock has the counts, but only if you send the X-Api-Key header.

Joining two answers: both lists use the same id for a product, and that is the only thing that links them. Turn the stock list into a Dictionary<int, int> that maps each id to its count. Then stock[product.GetProperty("id").GetInt32()] gives any product's stock in one step, with no searching.

Sorting JSON items: Sort() can't compare two JsonElements on its own. Use OrderBy and give it a function that takes one item and returns the value to sort by. For example, to sort a cart by price:

int ByPrice(JsonElement item) {
    return item.GetProperty("price").GetInt32();
}

cart = cart.OrderBy(ByPrice).ToList();

Pass the function without parentheses: OrderBy calls it on every item for you, and ToList() turns the result back into a list. Your script must print exactly these lines:

Lamp: 8 left, price 14
Notebook: 0 left, price 3
Plant: 0 left, price 6

Your task: SUPPLIER and API_KEY are given. Read /prices, read /stock with the key, build the dictionary stock from id to count, then print every product with fewer than 10 left, sorted by name: its name with a colon, its stock, left, price and its price.


Assignment
Follow the Coding Tutorial to build the restock report: two requests, a dictionary of stock by id, the printing loop and a sort by name.


Hint
Build stock before the product loop, starting from new Dictionary<int, int>(). In the loop, compare the product's stock with 10 using <. Just before the loop, set prices to prices.OrderBy(ByName).ToList(), with no parentheses after ByName.


STEP 1 OF 12
    Ctrl + Enter to check

    Web Restock Report 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