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

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:\r\nID - Priority");
foreach(Task t in Tasks)
   Debug.Print(" " + t.ID + " - " + t.Priority);

// Sort the tasks

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

Here is the output from executing the code above:

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

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.


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: November 17, 2015 Although enterprise adoption of open source has accelerated, some are still wary of it. But not all open source technologies are the same: some are designed with enterprises in mind. In this webinar, we'll discuss trends in open source development, innovation impacts, and what it means for the future.

  • Moving from an on-premises environment to Office 365 does not remove the need to plan for disruptions or reduce the business risk requirements for protecting email services. If anything, some risks increase with a move to the cloud. Read how to ease the transition every business faces if considering or already migrating to cloud email. This white paper discusses: Setting expectations when migrating to Office 365 Understanding the implications of relying solely on Exchange Online security Necessary archiving …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date