Home >Backend Development >C++ >How Can I Sort a List by an Object Property in C# Using LINQ?
Efficiently Sorting Lists of Objects in C# using LINQ
When dealing with lists of custom objects in C#, the need to sort these lists based on specific object properties frequently arises. For instance, imagine a list of Order
objects, each possessing properties like OrderId
, OrderDate
, Quantity
, and Total
. This article demonstrates how to efficiently sort such lists using LINQ.
Leveraging LINQ for Sorting
LINQ (Language Integrated Query) offers a clean and powerful way to query and manipulate data, including sorting lists. Let's explore how to sort our list of Order
objects.
To sort the list by OrderDate
in ascending order, use the OrderBy()
method:
<code class="language-csharp">List<Order> sortedOrders = objListOrder.OrderBy(o => o.OrderDate).ToList();</code>
This creates a new list, sortedOrders
, containing the original Order
objects sorted by their OrderDate
property. The lambda expression o => o.OrderDate
specifies the sorting criteria.
For descending order sorting by OrderId
, employ the OrderByDescending()
method:
<code class="language-csharp">List<Order> sortedOrders = objListOrder.OrderByDescending(o => o.OrderId).ToList();</code>
The flexibility of LINQ extends to multi-level sorting. For example, to sort primarily by OrderDate
and then by OrderId
(both ascending), use ThenBy()
:
<code class="language-csharp">List<Order> sortedOrders = objListOrder.OrderBy(o => o.OrderDate).ThenBy(o => o.OrderId).ToList();</code>
This approach provides a concise and efficient method for complex sorting scenarios, making it a preferred technique for managing lists of objects in C#.
The above is the detailed content of How Can I Sort a List by an Object Property in C# Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!