Home > Backend Development > C++ > How Can I Sort a List by an Object Property in C# Using LINQ?

How Can I Sort a List by an Object Property in C# Using LINQ?

Susan Sarandon
Release: 2025-02-01 08:07:11
Original
165 people have browsed it

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:

List<Order> sortedOrders = objListOrder.OrderBy(o => o.OrderDate).ToList();
Copy after login

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:

List<Order> sortedOrders = objListOrder.OrderByDescending(o => o.OrderId).ToList();
Copy after login

The flexibility of LINQ extends to multi-level sorting. For example, to sort primarily by OrderDate and then by OrderId (both ascending), use ThenBy():

List<Order> sortedOrders = objListOrder.OrderBy(o => o.OrderDate).ThenBy(o => o.OrderId).ToList();
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template