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. Which LINQ method would you use to sort a collection of integers in descending order?
Select one option to check your answer.
2. What is the correct way to perform a multi-level sort on a collection, first by LastName ascending, then by FirstName descending?
Select one option to check your answer.
3. What happens if you call ThenBy without a preceding OrderBy or OrderByDescending in a LINQ query?
Select one option to check your answer.
4. Which statement about LINQ sorting methods is true?
Select one option to check your answer.
5. When sorting a list of strings with LINQ, what should you consider to ensure consistent ordering?
Select one option to check your answer.
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.
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.
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.





