Welcome back to our series on LINQ in .NET! If you missed previous installments, check them out, here:
In this episode, we’ll look at sorting data using LINQ. Whether you’re working with collections of objects in memory or querying a database, LINQ (Language-Integrated Query) provides a seamless and expressive way to sort data.
Understanding Sorting in LINQ
LINQ provides two primary operators for sorting:
OrderBy
: Sorts the elements of a sequence in ascending order.OrderByDescending
: Sorts the elements of a sequence in descending order.
These operators can be applied to various data sources, including arrays, lists, and even database queries.
Basic Sorting with OrderBy
Let’s start with a simple example. Imagine you have a list of numbers that you want to sort in ascending order:
int[] numbers = { 5, 1, 9, 3, 7 }; var sortedNumbers = numbers.OrderBy(n => n); foreach (var number in sortedNumbers) { Console.WriteLine(number); }
Sorting with OrderByDescending
If you need to sort in descending order, you can use the OrderByDescending
method:
int[] numbers = { 5, 1, 9, 3, 7 }; var sortedNumbersDesc = numbers.OrderByDescending(n => n); foreach (var number in sortedNumbersDesc) { Console.WriteLine(number); }
This sorts the numbers from highest to lowest.
Sorting Complex Objects
Sorting is even more powerful when working with complex objects. Suppose you have a list of Person
objects, and you want to sort them by their LastName
:
public class Person { public string FirstName { get; set; } public string LastName { get; set; } } var people = new List<Person> { new Person { FirstName = "John", LastName = "Doe" }, new Person { FirstName = "Jane", LastName = "Smith" }, new Person { FirstName = "Michael", LastName = "Johnson" } }; var sortedPeople = people.OrderBy(p => p.LastName); foreach (var person in sortedPeople) { Console.WriteLine($"{person.LastName}, {person.FirstName}"); }
Here, the OrderBy
method sorts the Person
objects based on their LastName
property.
ThenBy and ThenByDescending for Multi-Level Sorting
What if you want to sort by multiple criteria? LINQ provides the ThenBy
and ThenByDescending
methods to allow for secondary sorting. For instance, if you want to sort first by LastName
and then by FirstName
, you can do so as follows:
var sortedPeople = people .OrderBy(p => p.LastName) .ThenBy(p => p.FirstName); foreach (var person in sortedPeople) { Console.WriteLine($"{person.LastName}, {person.FirstName}"); }
If two people have the same LastName
, the ThenBy
method will sort them by FirstName
.
Sorting with LINQ to SQL
Sorting with LINQ isn’t limited to in-memory collections. You can also sort data directly from a database using LINQ to SQL. Here’s an example where you sort customers by their City
:
var sortedCustomers = dbContext.Customers.OrderBy(c => c.City); foreach (var customer in sortedCustomers) { Console.WriteLine($"{customer.City}: {customer.Name}"); }
This example assumes you have a Customers
table with a City
column. LINQ translates this query into SQL, ensuring efficient execution.
Conclusion
Sorting data with LINQ is both powerful and expressive. Whether you’re working with simple data types or complex objects, LINQ provides the flexibility to sort by one or multiple criteria in either ascending or descending order. By leveraging OrderBy
, OrderByDescending
, ThenBy
, and ThenByDescending
, you can organize your data precisely as needed, all with clean and readable code.
In the next part of this series, we’ll explore how to filter data using LINQ, allowing you to narrow down your data sets to just what you need. Stay tuned!