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
Now I want to sort the list based on one property of the Order
object, for example I need to sort it by the order date or order id.
How can i do this in C#?
A Classical Object Oriented Solution
First I must genuflect to the awesomeness of LINQ.... Now that we've got that out of the way
A variation on JimmyHoffa answer. With generics the
CompareTo
parameter becomes type safe.This default sortability is re-usable of course. That is each client does not have to redundantly re-write the sorting logic. Swapping the "1" and "-1" (or the logic operators, your choice) reverses the sort order.
Here is a generic LINQ extension method that does not create an extra copy of the list:
To use it:
I recently built this additional one which accepts an
ICompare<U>
, so that you can customize the comparison. This came in handy when I needed to do a Natural string sort:Using LINQ
Make use of LiNQ
OrderBy
If you need to sort the list in-place then you can use the
Sort
method, passing aComparison<T>
delegate: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.The easiest way I can think of is to use Linq: