Sorting a list by a property in C# is one of the most common tasks developers face. Whether you are building an e-commerce application, managing employee records, or handling data-driven dashboards, understanding how to sort objects efficiently is essential.
Sorting allows you to:
In C#, lists are often represented using the List<T> collection. Each object in the list can have multiple properties. Sorting can be done based on one or more of these properties.
The List.Sort() method allows you to define a custom comparison to sort objects by a specific property.
using System; using System.Collections.Generic; public class Product { public string Name { get; set; } public decimal Price { get; set; } } public class Program { public static void Main() { List<Product> products = new List<Product> { new Product { Name = "Laptop", Price = 1200 }, new Product { Name = "Mouse", Price = 25 }, new Product { Name = "Keyboard", Price = 75 } }; // Sort by Price products.Sort((x, y) => x.Price.CompareTo(y.Price)); foreach (var product in products) { Console.WriteLine($"{product.Name} - ${product.Price}"); } } }
Explanation: Here, we use a lambda expression to compare the Price property of each product. The CompareTo method ensures the list is sorted in ascending order.
LINQ provides a more readable and declarative way to sort lists.
using System; using System.Collections.Generic; using System.Linq; public class Employee { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { List<Employee> employees = new List<Employee> { new Employee { Name = "Alice", Age = 30 }, new Employee { Name = "Bob", Age = 25 }, new Employee { Name = "Charlie", Age = 35 } }; var sortedEmployees = employees.OrderBy(e => e.Age).ToList(); foreach (var employee in sortedEmployees) { Console.WriteLine($"{employee.Name} - {employee.Age}"); } } }
LINQ (Language-Integrated Query) is a powerful feature in C# that allows developers to query, filter, and sort collections in a clean and readable way. Sorting a list by a property using LINQ is one of the most common tasks for developers handling collections of objects.
Here’s a practical example of sorting a list of objects by a single property using LINQ.
using System; using System.Collections.Generic; using System.Linq; public class Employee { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { List<Employee> employees = new List<Employee> { new Employee { Name = "Alice", Age = 30 }, new Employee { Name = "Bob", Age = 25 }, new Employee { Name = "Charlie", Age = 35 } }; // Sort employees by Age using LINQ var sortedEmployees = employees.OrderBy(e => e.Age).ToList(); foreach (var employee in sortedEmployees) { Console.WriteLine($"{employee.Name} - {employee.Age}"); } } }
Sometimes you need to sort by more than one property. LINQ makes this simple:
var sortedEmployees = employees .OrderBy(e => e.Department) .ThenByDescending(e => e.Salary) .ToList();
Explanation: Here, employees are first sorted by Department in ascending order. If multiple employees are in the same department, they are sorted by Salary in descending order.
| Use Case | Example |
|---|---|
| E-commerce | Sort products by price, rating, or availability using LINQ. |
| Employee Management | Sort employees by age, department, or salary using LINQ. |
| Event Scheduling | Sort events by date, time, and priority for calendars. |
| Reporting | Sort sales and revenue data for dashboards using LINQ queries. |
Using LINQ in C# to sort a list by a property is a clean, efficient, and highly readable approach. Whether sorting by a single property or multiple properties, LINQ simplifies the process and is ideal for both beginner and intermediate developers handling collections of objects in real-world applications.
Sometimes, you may want to sort objects by more than one property. For example, sorting first by Department and then by Salary:
var sortedEmployees = employees .OrderBy(e => e.Department) .ThenByDescending(e => e.Salary) .ToList();
This approach allows flexible sorting and ensures predictable order when primary keys are equal.
| Use Case | Example |
|---|---|
| E-commerce | Sort products by price, rating, or popularity. |
| Employee Management | Sort employees by age, name, or department. |
| Event Scheduling | Sort events by date and time for calendars. |
| Reporting | Sort sales data for charts and dashboards. |
Sorting a list by a property in the object in C# is a fundamental skill for any developer. Using List.Sort() or LINQ OrderBy(), you can organize your data efficiently and improve readability, performance, and usability. With practice, sorting complex objects becomes straightforward and highly effective in real-world applications.
The easiest way is to use LINQ's OrderBy() or OrderByDescending() methods. They are readable and support multi-property sorting with ThenBy().
Yes, using LINQ OrderBy() returns a new sorted list, leaving the original list unchanged.
Use OrderBy() for the primary property and ThenBy() or ThenByDescending() for additional properties.
generally faster for large lists because it sorts in place, while OrderBy() creates a new list. Choose based on readability vs. performance needs.
You can handle nulls using the null-coalescing operator (??) or a custom comparison to avoid exceptions:
products.Sort((x, y) => (x.Price ?? 0).CompareTo(y.Price ?? 0));
Copyrights © 2024 letsupdateskills All rights reserved