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#?
Anybody working with nullable types,
Value
is required to useCompareTo
.objListOrder.Sort((x, y) => x.YourNullableType.Value.CompareTo(y.YourNullableType.Value));
To do this without LINQ on .Net2.0:
If you're on .Net3.0, then LukeH's answer is what you're after.
To sort on multiple properties, you can still do it within a delegate. For example:
This would give you ascending dates with descending orderIds.
However, I wouldn't recommend sticking delegates as it will mean lots of places without code re-use. You should implement an
IComparer
and just pass that through to yourSort
method. See here.And then to use this IComparer class, just instantiate it and pass it to your Sort method:
An improved of Roger's version.
The problem with GetDynamicSortProperty is that only get the property names but what happen if in the GridView we use NavigationProperties? it will send an exception, since it finds null.
Example:
"Employee.Company.Name; " will crash... since allows only "Name" as a parameter to get its value.
Here's an improved version that allows us to sort by Navigation Properties.
From performance point of view the best is to use a sorted list so that data is sorted as it is added to result. Other approaches need at least one extra iteration on data and most create a copy of data so not only performance but memory usage will be affected too. Might not be an issue with couple of hundreds of elements but will be with thousands, especially in services where many concurrent requests may do sorting at the same time. Have a look at System.Collections.Generic namespace and choose a class with sorting instead of List.
And avoid generic implementations using reflection when possible, this can cause performance issues too.