.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
Tasks.Sort();

// 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:

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.



Comments

  • 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: February 12, 2015 The evolution of systems engineering with the SysML modeling language has resulted in improved requirements specification, better architectural definition, and better hand-off to downstream engineering. Agile methods have proven successful in the software domain, but how can these methods be applied to systems engineering? Check out this webcast and join Bruce Powel Douglass, author of Real-Time Agility, as he discusses how agile methods have had a tremendous …

  • The mobile market is white hot. Building a well-crafted product development plan that addresses market research, strategy, design, and development will provide the greatest chance for success. Each phase of an app's lifecycle is critical to the its overall success and feeds into the next step of the process of product development for the app. This white paper examines the five key phases of mobile app creation, one by one, to understand how they work together to help create a successful mobile app.

Most Popular Programming Stories

More for Developers

RSS Feeds

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