[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Sort objects in C#

Sort objects

This example shows how you can easily sort objects in C#.

Sorting algorithms are absolutely fascinating and I recommend that everyone study them at some point. Different algorithms demonstrate interesting and useful techniques such as recursion, divide-and-conquer, linked data structures, heaps, balanced trees, and randomization to prevent worst-case performance. (You can learn more about some of them and about other useful algorithms in my book Essential Algorithms: A Practical Approach to Computer Algorithms.)

However, the .NET Framework provides some very good sorting tools so, unless the data has a special structure that you can use to your advantage, you will probably not beat the built-in routines by much. So follow one of my standard pieces of advice:

First make it work. Then make it work faster if necessary.

To sort an array, you can use the Array.Sort method. This example builds an array of random numbers named numbers. It displays the list, sorts it using the following code, and displays the sorted version.

Array.Sort(numbers);

It's hard to imagine anything simpler!

Unfortunately this method doesn't work with an array of objects. For example, suppose you build a Person class with the usual fields: FirstName, LastName, Street, City, State, Zip, Phone, and so forth. There's no way the Array.Sort method can know how you would want a list of these objects sorted. Should it sort by name? Last name first or last? By ZIP code, perhaps for a mailing list?

Basic Sorting

One way to give Array.Sort the ability to sort these objects is to make the class implement the IComparable interface.

(An interface defines properties, methods, and events that the class must provide but it doesn't say how they must be provided. The IComparable interface says the class provides a CompareTo method that takes an object as a parameter and returns a value less than, equal to, or greater than 0 to indicate whether this object (for example, a Person) should be considered less than, equal to, or greater than another object (another Person).

If the Person implements IComparable, then the Array.Sort can use the CompareTo method to compare two Person objects and it can sort an array of Persons.

To implement an interface, make the class "inherit" from the interface. This program's Person class uses the following declaration to indicate that it implements the generic IComparable interface that compares the class's objects to other Person objects.

class Person : IComparable<Person>

The following code shows the Person class's CompareTo method.

// Compare two Person's names. public int CompareTo(object obj) { return ToString().CompareTo(person.ToString()); }

When it starts, the program creates an array of Person objects named people and then uses the following code to sort them.

Array.Sort(people);

Easy, peasy. But suppose you sometimes want to sort Person objects in some other way. For example, suppose you sometimes want to sort them last-name-first. The Person class's CompareTo method sorts first name first so it won't do that.

Custom Sorting

To handle this problem, the Array.Sort method can take as a second parameter an object that implements the IComparer interface. That interface requires a class to provide a Compare method that compares two objects. Array.Sort uses the comparer to compare two Person objects while it sorts.

The following code shows the IComparer class used by this example.

class PersonComparer : IComparer<Person> { // Compare two Persons. public int Compare(Person person1, Person person2) { string name1 = person1.LastName + "," + person1.FirstName; string name2 = person2.LastName + "," + person2.FirstName; return name1.CompareTo(name2); } }

This method compares two Person objects and returns -1, 0, or 1 to indicate whether the first should be regarded as less than, equal to, or greater than the second in last-name-first order.

The example program uses the following code to sort a list of Person objects in last-name-first order.

PersonComparer comparer = new PersonComparer(); Array.Sort(people, comparer);

(The program also overrides the Person class's ToString method to allow its ListBoxes to display Person objects nicely. For more information, see Override ToString to allow controls such as ListBox to display objects in C#.)

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.