Skip to Content
Course content

188: OrderBy, OrderByDescending, ThenBy

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Sorting data is one of those things you'll do in almost every single professional project. In C#, we handle this primarily through LINQ. I'm assuming you've already got the hang of basic lambdas, so we can jump straight into the logic.

How do I actually sort a list?

If you just need a simple sort, you'll use OrderBy for ascending order (A-Z, 1-10) or OrderByDescending for the reverse. Let's say we're building a simple inventory system for a hobby shop.

public class Product
{
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

var inventory = new List<Product>
{
    new Product { Name = "Acrylic Paint", Category = "Art", Price = 12.50m },
    new Product { Name = "Sketchbook", Category = "Art", Price = 15.00m },
    new Product { Name = "Gaming Mouse", Category = "Tech", Price = 45.00m },
    new Product { Name = "Mechanical Keyboard", Category = "Tech", Price = 80.00m },
    new Product { Name = "LED Strip", Category = "Tech", Price = 15.00m }
};

// Sort by price, cheapest first
var cheapestFirst = inventory.OrderBy(p => p.Price);

// Sort by name, Z to A
var reverseAlpha = inventory.OrderByDescending(p => p.Name);

One thing to keep in mind: these methods don't actually change the inventory list itself. They return a new sequence. If you want the result back in a List, you'll need to tack .ToList() onto the end.

What if I need to sort by a second property?

Real-world data is rarely that simple. Usually, you want to sort by a category first, and then sort the items within that category by something else. This is where ThenBy and ThenByDescending come in.

If I want my inventory grouped by category, but I want the most expensive items in each category to appear first, I'd do this:

var sortedInventory = inventory
    .OrderBy(p => p.Category)
    .ThenByDescending(p => p.Price);

The OrderBy handles the primary sort. When two items have the same category (a "tie"), ThenByDescending steps in to break that tie using the price. It's a clean, readable chain.

Why can't I just call OrderBy twice?

I see this mistake all the time when developers are first starting with LINQ. You might be tempted to do this:

// DON'T DO THIS
var wrongWay = inventory.OrderBy(p => p.Category).OrderBy(p => p.Price);

Here is the catch: OrderBy is a "destructive" sort in terms of the sequence logic. The second OrderBy doesn't supplement the first one; it completely replaces it. In the example above, your list would end up sorted by price, and the category sort would be totally ignored. Always use ThenBy for every subsequent sorting level.




📋 Practical Task

Exercise: Sorting a High-Score Leaderboard

You are building a leaderboard for a game. You have a list of Player objects, each with a Username (string) and a Score (int).

Create a list of at least 5 players, ensuring that at least two players have the exact same score. Write a LINQ query to sort the players based on these rules:

  • Primary sort: Score in descending order (highest score at the top).
  • Secondary sort: Username in ascending order (alphabetical) to break ties between players with the same score.

Print the final sorted list to the console to verify that the ties were broken correctly by the username.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.