Base Data Types
  Sort an array
  Format a string
  Parse datatypes
  Compare references
  Compare object values
  Use mathematical functions

Get URL for this page

How Do I...Sort an array?

This sample illustrates sorting the elements in an array. Using the Array.Sort method, you can sort any array whose elements implement the IComparable interface. You can also sort arrays of your own types as long as they implement IComparable. If a type does not implement IComparable (or if you want to customize the sort order) you can still use Array.Sort if you provide a Comparer, such as the MyTypeNameComparer shown in this sample.

 
VB Sort.aspx

[Run Sample] | [View Source]

Sorting is a standard basic function of any group of objects or data. In the following examples, sorting is performed specifically on an array. Most data types can be sorted when they are stored in an array, as long as they support the IComparable interface. The easiest way to sort an array is to call the Sort method, passing in the array you want to sort. The following code example illustrates populating an array with names, and then calling the Sort method to organize those names in alphabetical, ascending order.


Dim stringArray() As String ={"Michael", "mary", "Robert", _
		"Abigail", "lorne", "Therese", "terrence", "Samantha"}

Array.Sort(stringArray)
VB

If you want to sort your array in descending order, call the Sort method, and then call the Reverse method, passing in the array you want to sort in each case. Note that calling Reverse reverses the existing entries in the array. To get a descending array, you need to sort the array before reversing it.


Dim intArray() As Integer = {43, 12, 1, 17, 23, 36, 11}

Array.Sort(intArray)
Array.Reverse(intArray)
VB

You might want to sort more than predefined data types. What if you have defined your own class and want to sort an array of members of that class? To do this, implement the IComparable interface on that class, and then define the rule for comparing an instance of that class to other objects. Generally, you can do this by selecting a variable inside that class that can be used to determine the way your class should be sorted (for example, you might want to sort by 'LastName' for the class 'Employee').

The following code example defines MyType, which has two pieces of information: name and age. In this case, the sort mechanism is based on age. You need to include a CompareTo method, and define the rules for comparison in that method. When one object is compared to another, the return value from this method is used to determine whether the object being compared is greater than or less than the current object (a negative value indicates the comparing object is less than the current object).


'  imports statements...
Imports System
Imports System.Collections

Class MyType: Implements IComparable

	'  Property, method, and field declarations...
	'  included are an Age, and a Name property

	Public Function CompareTo (ByVal o as Object) As Integer _
				Implements IComparable.CompareTo
		If Not (TypeOf o Is MyType) Then
			throw new ArgumentException ("o must be of type 'MyType'")
		End If

	        Dim v As MyType = CType(o, MyType)
	        CompareTo = _age - v._age
	End Function
End Class
VB

To sort members of this class, populate an array with entries and call the Array.Sort method. Because you implemented the IComparable interface, Sort knows to use the CompareTo method of the class to determine how to sort the array.


Dim myTypeArray() As MyType = New MyType() { New MyType("Max",23), _
		New MyType("Lisa",47), New MyType("Andrea",35), _
		New MyType("Mel",29), New MyType("Andrew",32), New MyType("Ahmed",35) }

Array.Sort(myTypeArray)
VB

The Sort method can also accept a class defining the comparison mechanism to apply to that array, if you want to override the default sorting that will be provided. You can make your own comparison mechanism by defining a class that implements the IComparer interface. By defining a comparer in this manner, you can specify different sorting techniques.

The following code example defines a comparer that allows you to compare the names, rather than ages, inside the MyType class. This means that you won't be able to apply the comparer to other classes, but you can define different modes of sorting this specific object.


class MyTypeNameComparer: Implements IComparer

 	Public Function CompareTo(ByVal x As Object, ByVal y As Object) As Integer _
				Implements IComparer.Compare

		If Not (TypeOf x is MyType And TypeOf y is MyType) Then
				Throw New ArgumentException _
				("The objects to compare must be of type 'MyType'")
		End If

		Dim tempObj1 As String = CType(x, MyType).Name
		Dim tempObj2 As String = CType(y, MyType).Name

		CompareTo = tempObj1.ToString().CompareTo (tempObj2.ToString ())
	End Function
End Class
VB

To use the comparer, you have to pass Array.Sort the comparer as the second parameter. After it is sorted, you can use a foreach (For Each in VB) statement to iterate through the array, and print out the elements to the Console, formatting the information for easier reading.


Array.Sort(myTypeArray, new MyTypeNameComparer())

Dim t As MyType

For Each t in myTypeArray
	Console.WriteLine("Name = {0, -7}, Age = {1}", t.Name, t.Age)
Next t
VB

Note that the Sort method also allows you to sort only a specified section of an array. See the .NET Framework SDK for more information on Sort, Reverse, and other Array functions.

Summary

  1. To sort a set of like elements (specifically, an array) in ascending order, use the Sort method on an array.
    The basis of the sort used will be the datatype of the elements in the array (datatype of the array).
  2. To sort the elements of an array in descending order, use the Sort method, followed by the Reverse method.
  3. To sort your own arrays of objects, implement the IComparable interface on that object.
    You have to define a CompareTo method inside your object in order to specify how this object should be compared.
  4. To define a specific way to compare objects, create a class that implements the IComparer interface.
    Inside this class, you must include a Compare method that accepts two objects to compare.
    It helps to know how you want to compare those objects, and which objects should be allowed to use the interface you define.


Copyright 2001 Microsoft Corporation. All rights reserved.