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#?
Doing it without Linq as you said:
Then just call .sort() on your list of Orders
Based on GenericTypeTea's Comparer :
we can obtain more flexibility by adding sorting flags :
In this scenario, you must instantiate it as MyOrderingClass explicitly( rather then IComparer )
in order to set its sorting properties :
Simplest way to order a list is to use
OrderBy
If you want to order by multiple columns like following SQL Query.
To achieve this you can use
ThenBy
like following.// Totally generic sorting for use with a gridview
You can do something more generic about the properties selection yet be specific about the type you're selecting from, in your case 'Order':
write your function as a generic one:
and then use it like this:
You can be even more generic and define an open type for what you want to order:
and use it the same way:
Which is a stupid unnecessary complex way of doing a LINQ style 'OrderBy', But it may give you a clue of how it can be implemented in a generic way
Please let me complete the answer by @LukeH with some sample code, as I have tested it I believe it may be useful for some: