Sort Items in an Array or ArrayList

Problem

You need to sort the items in an array or ArrayList. The items in the array or ArrayList implement IComparable (as do all basic .NET data types).

Solution

Use the Array.Sort or ArrayList.Sort methods.

Discussion

Both the Array and ArrayList types expose a Sort method. This method uses an optimized sort algorithm and compares objects using the IComparable interface. If the objects in the array don’t support this interface, you’ll need to use a custom comparer (as explained in recipe Sort Non-Comparable Items in an Array or ArrayList). If there’s more than one type of object in the same collection, you won’t be able to sort it.

The following example sorts strings in an ArrayList. In this case, the type of sort ...

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.