Implementing IComparer for Sorting Custom Objects

Per my technical blog:

In a previous post I discussed the usefulness of implementing IComparable for your classes to assist in sorting your custom objects in ArrayLists.  When you call Sort() on the ArrayList, the default implementation of IComparer is called which uses QuickSort.  QuickSort calls the IComparable implementation of CompareTo() on each of your objects in the ArrayList.

Implementing IComparable for Sorting Custom Objects

Sometime this isn't enough and you will want to pass in your own IComparer for more flexibility, such as to allow you to specify by which field you want to sort the custom objects in the ArrayList.

 

IComparer Defined

Compares two objects and returns a value indicating whether one is less than, equal to or greater than the other.

int Compare(object x, object y);

 

Rather than calling the Sort() method on the ArrayList and using the default IComparer, we are going to use an overloaded method of the ArrayList Sort method which allows us to pass in our own IComparer:

 

Sort(IComparer comparer)

public virtual void Sort(IComparer comparer);

 

Read more here.

posted on Sunday, March 06, 2005 8:43 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices