O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required