.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

  • Cisco and Intel have harnessed flash memory technology and truly innovative system software to blast through the boundaries of today's I/O-bound server/storage architectures. See how they are bringing real-time responsiveness to data-intensive applications—for unmatched business advantage. Sponsored by Cisco and Intel® Partnering in Innovation

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds