Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort a List<T> by a property in the object

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#?

like image 562
Shyju Avatar asked Jul 22 '10 13:07

Shyju


People also ask

How do you sort a class list 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.


2 Answers

The easiest way I can think of is to use Linq:

List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList(); 
like image 128
Lazarus Avatar answered Sep 23 '22 05:09

Lazarus


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.

like image 25
LukeH Avatar answered Sep 25 '22 05:09

LukeH