
n .NET, sorting arrays or collections of primitive types is a relatively simple task. Most developers understand that for a collection of numbers or strings, the runtime will know how to compare these values. However, some developers are left wondering how to sort complex objects. For example, what if you wanted to sort an array of
FileInfo objects by size rather than name?
After witnessing one fellow developer attempt to code his own
BubbleSort algorithm because he could not find another way to sort an array of his custom objects, I felt this article would help spread the word about the rich sorting capabilities supported by .NET.
Sorting Arrays and ArrayLists
Sorting an array composed of primitive data types such as strings and integers is straightforward. The Array class contains a static method called Sort. This method takes in an existing array object and sorts it. The following code demonstrates how simple it can be:
Dim aryBeatles() As String = {"John", "Paul", "George", "Ringo"}
Array.Sort(aryBeatles)
' New order of the aryBeatles array:
'
' aryBeatles
' ----------
' George
' John
' Paul
' Ringo
Sorting an ArrayList is equally easy but somewhat different. The ArrayList is based on an Array. It internally manages an array while exposing properties and methods to make working with them easier. Taking from the example above, here is a demonstration of sorting an ArrayList:
'Base the arraylist on the aryBeatles array.
Dim lstBeatles As New ArrayList(aryBeatles)
lstBeatles.Sort()
Aside from the syntactical differences, the ArrayList still internally relies on the
Array.Sort method to sort its contents. The
Array.Sort method is the core of all sorting in. NET. Because of this, for the rest of the article I will use arrays to demonstrate the sorting capabilities of the .NET Framework.