Start learning free

LESSON 28 OF 173 · BACKEND: YOUR FIRST API

Sort the List in C#

Practice

Clients often want a list in a useful order: the cheapest products first, or names from A to Z. C#'s OrderBy gives you the items in order, and ToList() turns them into a new list. It can't compare two dictionaries, though, so you tell it what to compare with a key function: a function that takes one item and returns the value to sort by.

int ByStars(Dictionary<string, object> review) {
    return (int)review["stars"];
}

// reviews: ana with 5 stars, bo with 3 stars
var fewestFirst = reviews.OrderBy(ByStars).ToList();
// bo (3 stars) first, then ana (5 stars)

Write OrderBy(ByStars) without parentheses after ByStars: you hand over the function itself, and OrderBy calls it on each item. OrderBy never changes the list it reads, so the original list keeps its order.

The client picks the order with a query parameter: ?sort=price or ?sort=name. The route already takes string? sort. Any other value is a mistake, so the shop answers 400 with an error. Without sort, the list keeps the shop's order, and the filters still work. The lists below show product names only; each item is a full product.

GET /products?sort=price  →  200  [Pen, Notebook, Mug, Lamp]
GET /products?sort=name  →  200  [Lamp, Mug, Notebook, Pen]
GET /products  →  200  [Mug, Notebook, Lamp, Pen]
GET /products?category=office&sort=price  →  200  [Pen, Notebook]
GET /products?sort=color  →  400  {"error": "Sort must be price or name"}

Your task: write two key functions, ByPrice and ByName. In GET /products, answer 400 for an unknown sort, and sort the filtered list by price or by name.


Assignment
Follow the Coding Tutorial to add sorting to GET /products.


Hint
Sort after the filter loop, so only the products that passed the filters get sorted. Give OrderBy the key function without parentheses, and end with .ToList() so result is a list again.


STEP 1 OF 10
    Ctrl + Enter to check

    Shop Sort 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