I would like to share a piece of code that can save
good amount of time.
You are having a Customer class with properties
Age, Dob, Name which are int, datetime and string respectively.
The Customer objects are stored in a list and for
custom sorting them based on different properties, we need to write code by
implementing IComparer. This could be a tedious task if lots of UI screens are
there and you need to write specific code for each screen. The problem is worse
if you wanted to sort ascending/descending and based on multiple
You can accomplish the above by using the following
class which implements IComparer interface.
The above class 'ReflectionComparer' has
constructor which takes the property on which the object to be
The constructor takes multiple property names so
that we can sort on multiple items. There is one overloaded constructor too,
which takes the SortOrder (Ascending/Descending).
You can just call the Sort method of the
array/ArrayList and pass the instance of above class to it.
Eg: list.Sort(new ReflectionComparer("Age"));
It contains 2 constructors which are explained
There is one core method named Compare() which takes
arguments x and y.
public int Compare(object x,
For each objects passed - the corresponding CompareTo() method is
called using Reflection.
The method GetMethodInfo() returns the "CompareTo" method info
object. Some optimizations were used there to reuse the same CompareTo()
MethodInfo object to speed up the sorting process.
The method GetValue() returns the value of property to be
compared. Here also Reflection is the underlying mechanism.
The attachment contains the test application which was created in
Visual Studio 2008. The test application provides us the UI to test various
scenarios and their corresponding time taken for execution in
Eventhough Reflection comparison will be slower
than normal comparisons, we can judiciously use the code above if the sorting
speed is within our expectations. The idea for the above comparer class is to
minimize the coding effort on doing the comparison code infra. In the above
screen shot, 10 thousand records were sorted within 1 second in my computer
having 3GHz speed. Reflection is slower but your computer is many times faster
than your requirement - then it is a right choice to use the code above. Happy