Lesson 15/31

Tutorials LINQ Mastery

ThenBy: Multi-level sorting

On this page

Secondary Sorting

What happens when two items have the same 'Primary' key? ThenBy allows you to specify subsequent sorting criteria.

1. Why NOT use another OrderBy?

A common mistake is calling .OrderBy(x => x.A).OrderBy(x => x.B). This actually throws away the first sort and re-sorts the entire list by B. To maintain the primary sort, you MUST use ThenBy.


// Correct way: Sort by LastName, then by FirstName
var sortedUsers = users.OrderBy(u => u.LastName)
                       .ThenBy(u => u.FirstName);
    

2. Infinite Levels

You can chain as many ThenBy or ThenByDescending calls as you need. C# handles the priority from left to right. This is essential for building complex data tables with multi-column sorting.

3. Architect Insight

Q: "Do multiple levels of sorting impact performance?"

Architect Answer: "Yes, each level adds a small amount of comparison logic. However, the biggest impact is on the database. In SQL, this becomes ORDER BY A, B, C. Ensure your DB composite indexes match your most common multi-column search patterns to keep queries optimized."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details