.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 11, 2015 New computing platforms, expanding information environments, recurrent security breaches and evolving regulatory frameworks are factors that security executives must contend with and address when developing their security strategy. In response to these dynamics, security executives are seeking stronger, more nimble and more pervasive security technologies to help protect business-critical information from unauthorized disclosure, loss or corruption. Yet with an …

  • Finance leaders have been talking about expanding the value-added role of their teams for a long time. The debate is no longer whether the finance and accounting function needs to become a more strategic partner to the rest of the business but rather how to get there. Technology innovation has caught up to this ambition, and what was once aspiration can be a reality – and the choice is now yours. Read this research report to learn how to make the most of information tools to enable innovation and growth.

Most Popular Programming Stories

More for Developers

RSS Feeds

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