火曜日, 11月 04, 2008

Programming.Practice.#.1: A Generic List Sorter using IComparer

Problem: Create a custom class that implements the necessary interfaces to allow an array of class to be sorted.
To create this custom class, I opted to implement IComparer as I wanted to have a comparisonType wherein any class property can be used as a sort filter. The use of generic T instead of object is also a good practice to avoid comparison of 2 different types.

I created a simple Person class in which instances are the ones to be sorted later on. :D


Now for the comparer class, I added a ComparisonType property, implemented Compare method of IComparer calling CompareTo method which does the processing.

Given the ComparisonType, System.Reflection's PropertyInfo will help get the corresponding reflected property type and property value. Once the values are compared, an int value (-1, 0, 1) is returned.


And now for the Sorting itself, using a console app as a sample, I made a List of type Person, created an instance of the comparer and called the Sort method of the List. I think, this sort works like Bubble Sort calling the comparer's Compare method each time.


As for the results, here are sample outputs given different ComparisonTypes. :D
ComparisonType = "FirstName"


ComparisonType = "LastName"



So that's it! Yet, this can still be refactored. Hope this practice code can help! :D

0 comments: