Sorting Objects in Collections

When you have selected the appropriate collection class for your application, you might still need to add functionality to the objects in the collection to achieve the desired results. For example, the Array and ArrayList classes give you the Sort method to sort objects into some order. However, when you call the Sort method, a run-time exception is thrown if the class of the elements in the collection does not support the IComparable interface.

Sorting with IComparable

If you want to support only a single sort order for your objects, you can implement the IComparable interface, which consists of a single method, CompareTo. When sorting, the system calls this method for a particular object in the collection to compare ...

Get Microsoft® .NET Compact Framework (Core Reference) 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.