Software Development

Easily sort values with the .NET Array class's Sort method

Tony Patton recently examined the <a target='_blank'href='http://www.techrepublic.com/article/5100-3513-6126663.html'>basic functionality of .NET arrays</a>; this week, he focuses on the Array class's Sort method, which simplifies sorting the contents of an array. He also explains how you can use other .NET features to institute custom sorting.

In a previous column, I discussed the basic functionality of .NET arrays. This week, I expand on this topic and focus on sorting the contents of an array. The Array class provides the Sort method, and there are various ways to use this method. I begin with the simple approach and end with custom sorting.

The Sort method

The simplest way to sort the contents of an array is by using the static Sort method of the Array class. Listing A provides a peek at using this approach by sorting a list of names.

The following output is generated; it shows the names listed before and after the sort method is called:

0. Howard, Ryan
1. Allen, Ray
2. Pujols, Albert
3. Iverson, Allen
0. Allen, Ray
1. Howard, Ryan
2. Iverson, Allen
3. Pujols, Albert

Here is the equivalent VB.NET:

Dim x As Integer
Dim names(3) As String
names(0) = "Howard, Ryan"
names(1) = "Allen, Ray"
names(2) = "Pujols, Albert"
names(3) = "Iverson, Allen"
For x = 0 To (names.Length - 1)
Console.WriteLine(CStr(x) + ". " + names(x).ToString())
Next x
Array.Sort(names)
For x = 0 To (names.Length - 1)
Console.WriteLine(CStr(x) + ". " + names(x).ToString())
Next x
Weekly .NET tips in your inbox
TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET.
Automatically sign up today!

The Sort method of the Array class is overloaded to provide various ways to sort the contents of an array. Now that you see how the simplest form of the method works, here are the other signatures:

  • Sort(Array, Array): Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array.
  • Sort(Array, IComparable): Sorts the elements in a one-dimensional Array using the specified IComparer interface.
  • Sort(Array, Array, IComparable): Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer interface.
  • Sort(Array, Integer, Integer): Sorts the elements in a section of a one-dimensional Array designated by the starting and ending positions (Integer values).
  • Sort(Array, Array, Integer, Integer): Sorts a section of a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array.
  • Sort(Array, Integer, Integer, IComparable): Sorts the elements in a section of a one-dimensional Array using the specified IComparer interface.
  • Sort(Array, Array, Integer, Integer, IComparable): Sorts a section of a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer interface.

You can sort an entire array or a portion of an array using the default behavior of the Array class; you can also specify a particular way to sort it via a specific IComparer interface. The example in Listing B uses two arrays, where one array contains the keys and the other array contains the actual items to sort. It is the same as the first example with the key array added.

The result is the array values (second array specified in the call to the Sort method) sorted according to values in the key array. Listing C contains the equivalent VB.NET code.

You could tweak the code a bit to sort only a subject of the array using the appropriate call to the Sort method. The following code takes the preceding example and only sorts the second and third elements of the array.

int[] keys = new int[4];
keys[0] = 11;
keys[1] = 3;
keys[2] = 8;
keys[3] = 5;
string[] names = new string[4];
names[0] = "Howard, Ryan";
names[1] = "Allen, Ray";
names[2] = "Pujols, Albert";
names[3] = "Iverson, Allen";
Array.Sort(keys, names, 1, 2);

Here is the equivalent VB.NET code:

Dim x As Integer
Dim keys(3) As Integer
keys(0) = 11
keys(1) = 3
keys(2) = 8
keys(3) = 5
Dim names(3) As String
names(0) = "Howard, Ryan"
names(1) = "Allen, Ray"
names(2) = "Pujols, Albert"
names(3) = "Iverson, Allen"
Array.Sort(keys, names, 1, 2)

Sorting custom objects

While the simple Sort method is wonderful, you cannot use it to automatically sort an array of custom data types. After all, how can you expect the .NET platform to know about any and all objects that may be created? However, you can define how custom objects should be sorted by using the IComparer or IComparable interface.

With these interfaces, you provide a method to compare object instances to facilitate sorting. The main difference between the two interfaces is you must include the comparing method within the class that uses the IComparable interface while the method is outside the class when IComparer is used. The full details of both interfaces are beyond this column, but I will use the IComparable interface to sort an array of custom classes.

In Listing D, I utilize the IComparable interface to place the sorting logic with its class. I create a Person class as shown in the code. Notice that it uses the IComparable interface and includes the CompareTo method to handle comparisons (when sorting).

This class is used in the next example where an array of Person objects is created. The key to the Person class is the CompareTo method (required by the IComparable interface) that is utilized during sorting. It compares the passed object to itself. Next, the Sort method is called on the array with the Person class' sorting mechanism utilized so the items are sorted according to the first name property for each object in the array. Listing E shows the Person object used and sorted. Listing F contains the equivalent VB.NET code, which has the Person class listed first.

Plenty of options

Regardless of the data, sorting always seems to arise as an issue. After all, people like to see data in some logical order. The .NET Array class provides the Sort method to simplify sorting the contents of an array either using its values or a separate array of key values. In addition, you may utilize other .NET features like the IComparable interface to institute custom sorting.

Miss a column?

Check out the .NET Archive, and catch up on the most recent editions of Tony Patton's column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

0 comments

Editor's Picks