Sort Non-Comparable Items in an Array or ArrayList

Problem

You want to sort an Array or ArrayList, but the items it contains do not implement IComparable.

Solution

Create a custom IComparer that can sort the type of object contained in the Array or ArrayList. Pass an instance of this IComparer object to the Sort method of the Array or ArrayList object.

Discussion

Some objects define a native sort order by implementing the IComparable interface. Others do not, either because there’s no obvious criteria to use for sorting, or because there are several equally valid sort criteria. In these cases, you can create a custom IComparer, which is an object with a single purpose in life—to sort a specific type of object.

There are two reasons that you might use ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.