Sorting Data with LINQ in C#
Quick Answer
LINQ in C# provides powerful methods like OrderBy and OrderByDescending to sort collections easily. You can sort data by one or multiple keys, in ascending or descending order, using these methods combined with ThenBy and ThenByDescending for secondary sorting.
Learning Objectives
- Explain the purpose of Sorting Data in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Sorting Data.
- Apply Sorting Data in a simple real-world scenario or practice task.
Introduction to Sorting Data with LINQ
Sorting data is a fundamental operation when working with collections in C#. LINQ (Language Integrated Query) offers intuitive methods to order data efficiently.
This tutorial introduces you to the core LINQ sorting methods, helping you organize data in ascending or descending order with ease.
Sorting data effectively is key to readable and maintainable code.
Basic Sorting with OrderBy and OrderByDescending
The OrderBy method sorts elements of a collection in ascending order based on a key you specify.
OrderByDescending does the opposite, sorting elements in descending order.
- OrderBy sorts ascending by default.
- OrderByDescending sorts descending.
- Both methods require a key selector function.
Example: Sorting Numbers
Here is how you can sort a list of integers in ascending and descending order using LINQ.
Sorting by Multiple Keys with ThenBy and ThenByDescending
When sorting by multiple criteria, use ThenBy or ThenByDescending after an initial OrderBy or OrderByDescending call.
This allows you to specify secondary, tertiary, and further sorting keys.
- ThenBy sorts the next key in ascending order.
- ThenByDescending sorts the next key in descending order.
- You can chain multiple ThenBy calls for complex sorting.
Example: Sorting Objects by Multiple Properties
Consider sorting a list of people first by last name ascending, then by first name descending.
Practical Examples of LINQ Sorting
Let's look at practical code examples demonstrating sorting numbers and complex objects.
Practical Example
This example sorts a list of integers in ascending and descending order using OrderBy and OrderByDescending.
This example sorts a list of Person objects first by LastName ascending, then by FirstName descending.
Examples
List<int> numbers = new List<int> { 5, 3, 8, 1, 4 };
var ascending = numbers.OrderBy(n => n);
var descending = numbers.OrderByDescending(n => n);
Console.WriteLine("Ascending: " + string.Join(", ", ascending));
Console.WriteLine("Descending: " + string.Join(", ", descending));This example sorts a list of integers in ascending and descending order using OrderBy and OrderByDescending.
var people = new List<Person> {
new Person { FirstName = "John", LastName = "Doe" },
new Person { FirstName = "Jane", LastName = "Doe" },
new Person { FirstName = "Alice", LastName = "Smith" }
};
var sortedPeople = people
.OrderBy(p => p.LastName)
.ThenByDescending(p => p.FirstName);
foreach (var person in sortedPeople)
{
Console.WriteLine($"{person.LastName}, {person.FirstName}");
}This example sorts a list of Person objects first by LastName ascending, then by FirstName descending.
Best Practices
- Use OrderBy or OrderByDescending as the first sorting method.
- Chain ThenBy or ThenByDescending for secondary sorting keys.
- Avoid unnecessary sorting by selecting only needed keys.
- Use lambda expressions for concise key selectors.
- Remember LINQ sorting is deferred execution until enumeration.
Common Mistakes
- Calling ThenBy or ThenByDescending without a preceding OrderBy or OrderByDescending.
- Forgetting that LINQ sorting methods return a new sorted sequence and do not modify the original collection.
- Using OrderBy multiple times instead of chaining ThenBy for multiple keys, which resets sorting.
- Not considering case sensitivity when sorting strings.
Hands-on Exercise
Sort a List of Products
Given a list of products with properties Name and Price, sort the list by Price ascending, then by Name descending.
Expected output: Products sorted by increasing price, and for equal prices, by name in descending order.
Hint: Use OrderBy for Price and ThenByDescending for Name.
Interview Questions
What is the difference between OrderBy and ThenBy in LINQ?
InterviewOrderBy is used to sort a collection by the first key, while ThenBy is used to specify additional sorting keys after an initial OrderBy.
Does LINQ sorting modify the original collection?
InterviewNo, LINQ sorting methods return a new sorted sequence and do not modify the original collection.
What is Sorting Data, and why is it useful?
BeginnerLINQ in C# provides powerful methods like OrderBy and OrderByDescending to sort collections easily.
MCQ Quiz
1. What is the best first step when learning Sorting Data?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Sorting Data?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. LINQ in C# provides powerful methods like OrderBy and OrderByDescending to sort collections easily.
B. Sorting Data never needs examples
C. Sorting Data is unrelated to practical work
D. Sorting Data should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- LINQ in C# provides powerful methods like OrderBy and OrderByDescending to sort collections easily.
- You can sort data by one or multiple keys, in ascending or descending order, using these methods combined with ThenBy and ThenByDescending for secondary sorting.
- Sorting data is a fundamental operation when working with collections in C#.
- LINQ (Language Integrated Query) offers intuitive methods to order data efficiently.
- This tutorial introduces you to the core LINQ sorting methods, helping you organize data in ascending or descending order with ease.
Summary
LINQ provides simple and powerful methods to sort data collections in C#.
OrderBy and OrderByDescending handle primary sorting, while ThenBy and ThenByDescending allow for multi-level sorting.
Using these methods effectively can make your data manipulation code clean and efficient.
Frequently Asked Questions
Can I sort a collection in place using LINQ?
No, LINQ sorting methods return a new sorted sequence and do not modify the original collection.
How do I sort a list of strings ignoring case?
Use OrderBy with a StringComparer, for example: list.OrderBy(s => s, StringComparer.OrdinalIgnoreCase).
What happens if I call OrderBy multiple times on the same collection?
Each OrderBy call resets the sorting, so only the last OrderBy will be effective. Use ThenBy for additional sorting keys.
What is Sorting Data?
LINQ in C# provides powerful methods like OrderBy and OrderByDescending to sort collections easily.
Why is Sorting Data important?
You can sort data by one or multiple keys, in ascending or descending order, using these methods combined with ThenBy and ThenByDescending for secondary sorting.
How should I practice Sorting Data?
Sorting data is a fundamental operation when working with collections in C#.

