C# Interview Question #47
What are OrderBy(), OrderByDescending(), ThenBy(), and ThenByDescending()?
LINQ & Querying Mid-Level Intermediate
Quick Interview Answer
These LINQ operators sort sequences. OrderBy sorts by the primary key in ascending order, while OrderByDescending sorts in descending order.
Detailed Explanation
These LINQ operators sort sequences. OrderBy sorts by the primary key in ascending order, while OrderByDescending sorts in descending order.
ThenBy and ThenByDescending add secondary sorting criteria after an OrderBy or OrderByDescending.
In EF Core, these operations normally translate into SQL ORDER BY clauses when applied before materialization.
Code Example
var result = products
.OrderBy(p => p.CategoryId)
.ThenByDescending(p => p.Price)
.ToList();