Home >Backend Development >C++ >How to Sort a List by Object Property Using LINQ?
Use linq to list
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).
The most direct method of sorting the attributes of List objects using linq is shown below:
<code class="language-csharp">List<Order> SortedList = objListOrder.OrderBy(o => o.OrderDate).ToList();</code>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!