Home > Backend Development > C++ > How to Sort a List by Object Property Using LINQ?

How to Sort a List by Object Property Using LINQ?

Linda Hamilton
Release: 2025-02-01 08:11:09
Original
580 people have browsed it

How to Sort a List by Object Property Using LINQ?

Use linq to list

Object attribute sorting

Question:

Suppose there is a class called Order, which includes Orderid, OrderDate, Quantity, and Total. There is now a list containing these Order objects that sort the list based on specific attributes (such as OrderDate or Orderid).

Using Linq solution:

The most direct method of sorting the attributes of List objects using linq is shown below:

In this example, ObjlistorDer is a list of ORDER objects. The OrderBY method is used to set up the order of the order of the OrderDate attribute. The result is assigned to the SortedList variable.

<code class="language-csharp">List<Order> SortedList = objListOrder.OrderBy(o => o.OrderDate).ToList();</code>
Copy after login
Explanation:

The Orderby method accepts a lambda expression as a parameter, which attributes should be sorted in which attributes should be specified in this expression. In this example, Lambda expression o = & gt; O.OrderDate is used to access the OrderDate property of each Order object. The result of the OrderBY method is a sorted Ienumerable

sequence. In order to convert this sequence back to the list, the Tolist method is used. SortedList now contains a list of orderly Order objects.

This method can be easily modified to sort by any other attributes in the Order class. Just simply change the attribute names in Lambda expressions, such as O = & GT; O.O.orderid.

The above is the detailed content of How to Sort a List by Object Property Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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