I have a class called Order
which has properties such as OrderId
, OrderDate
, Quantity
, and Total
. I have a list of this Order
class:
List<Order> objListOrder = new List<Order>(); GetOrderList(objListOrder); // fill list of orders
I want to sort the list based on one property of the Order
object; for example, either by the order date or the order id.
How can I do this in C#?
Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
The easiest way I can think of is to use Linq:
List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();
If you need to sort the list in-place then you can use the Sort
method, passing a Comparison<T>
delegate:
objListOrder.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));
If you prefer to create a new, sorted sequence rather than sort in-place then you can use LINQ's OrderBy
method, as mentioned in the other answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With