Reflection Comparer in C#

I would like to share a piece of code that can save good amount of time.

Scenario

You are having a Customer class with properties Ag, 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 properties.

image

Solution

You can accomplish the above by using the following class which implements IComparer interface.

image

The above class ‘ReflectionComparer’ has constructor which takes the property on which the object to be sorted.

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).

Invoking

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"));

ReflectionComparer Class Explained

It contains 2 constructors which are explained above.

There is one core method named Compare() which takes arguments x and y.

public int Compare(object x, object y)

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.

Test Application

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 seconds.

image

Summary

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 Coding.

Source

You can download the source from: www.c-sharpcorner.com rocks!!

Leave a Reply

Your email address will not be published. Required fields are marked *