Microsoft & .NETVisual C#.NET Tip: Sort Your Objects by Implementing the IComparable Interface

.NET Tip: Sort Your Objects by Implementing the IComparable Interface

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

To enable your classes to be able to support custom comparisons, your class needs to implement the IComparable interface. IComparable contains a single method, CompareTo(),that your class will have to implement. The CompareTo() method compares the current instance of an object to another object of the same type. The following Task example class shows what is needed to implement IComparable. The Task class has ID and Priority properties and a CompareTo() method that sorts Tasks based on their Priority. The CompareTo() method needs to return a negative value if the current object is “less than” the object being compared, zero if the current object is “equal to” the other object, or a positive value if the current object is “greater than” the object being compared. In this example, the Priority property is used for the comparison. Because it is an integer, determining the value to return from CompareTo() is straightforward. For more complex classes, the logic you use to determine what value to return may be much more involved.

public class Task : IComparable
{
   public int ID { get; set; }
   public int Priority { get; set; }

   public Task(int pID, int pPriority)
   {
      ID = pID;
      Priority = pPriority;
   }

   public int CompareTo(Object obj)
   {
      Task SomeTask = (Task)obj;

      // If this.Priority is less than SomeTask.Priority,
      // return a negative value
      // If this.Priority is equal to SomeTask.Priority,
      // return 0
      // If this.Priority is greater than SomeTask.Priority,
      // return a positive value
      return this.Priority - SomeTask.Priority;
   }
}

Sorting Tasks is now easy. The following code shows you how by creating an ArrayList and adding five Task objects with random priorities to it. The code then prints out a list of the Tasks in the order they were created, along with each Task’s priority, for reference. The Sort() method of the ArrayList object is called and finally the list of Tasks, now sorted by Priority, is printed again.

Random Rnd = new Random();
ArrayList Tasks = new ArrayList();

// Create tasks and assign them a random priority
for (int i = 1; i <= 5; i++)
   Tasks.Add(new Task(i, Rnd.Next(100)));

// Print out the unsorted list of tasks
Debug.Print("Unsorted:rnID - Priority");
foreach(Task t in Tasks)
   Debug.Print(" " + t.ID + " - " + t.Priority);

// Sort the tasks
Tasks.Sort();

// Print out the list of tasks that are now sorted by priority
Debug.Print("Sorted:rnID - Priority");
foreach (Task t in Tasks)
   Debug.Print(" " + t.ID + " - " + t.Priority);

Here is the output from executing the code above:

Unsorted:
ID - Priority
 1 - 95
 2 - 25
 3 - 82
 4 - 78
 5 - 42

Sorted:
ID - Priority
 2 - 25
 5 - 42
 4 - 78
 3 - 82
 1 - 95

You can see from the final output that the Task objects are now sorted by Priority. Once your class implements IComparable, sorting them becomes a matter of a single method call on the ArrayList containing your objects.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories