65.9K
CodeProject is changing. Read more.
Home

Sorting objects on their properties that do not have their own CompatreTo() implementation.

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.29/5 (6 votes)

Mar 15, 2006

1 min read

viewsIcon

17625

downloadIcon

125

Shows how to Sort objects on their properties that do not have their own CompatreTo() implementation with an example of Colored Balls in Pipe using GDI+.

Sample Image - Sort.jpg

Introduction

Let us take an example of Student objects, with properties Id (int), Name (String), Height (double) etc. If we need to sort a collection (say an Array or Arraylist) of student objects on their Ids, or Names or Heights all we need to do is, to implement the IComparable interface and use the CompareTo() method of the respective data type in the implementation for the CompareTo() method in the Student Class.

For example if i need to sort on the Id (an int), the following would be the implementation of the compareTo() function.

//comparing the int
public int CompareTo(object obj)
{
 if(obj is Student)
 {
  Student s = (Student) obj;
  return _nId.CompareTo(s._nId);
 }
 throw new ArgumentException("object is not a Student");
}

But what if i add a new property called EyeColor, which is of Type System.Drawing.Color that does not have its own CompareTo() Implementation?

We need to supply an implementation that tells the Array or the ArrayList how the two instances are decided as > or = or < when compared to each other.

I could sort out this problem by using the GetHashcode() of Color instance, which returns an integer which inturn has its own CompareTo() method to be readily used.

I wrote a sample application using this logic to sort colored balls in a pipe, in groups of the simillar color.

There are 2 classes one for pipe and the other for the Ball. In the ball implements the IComparable interface and its CompareTo() is as follows...


//comparing the color
public int CompareTo(object obj)
{
 if(obj is BallGDI)
 {
 BallGDI b = (BallGDI) obj;
 return _Colour.GetHashCode().CompareTo(b._Colour.GetHashCode());
 }
 throw new ArgumentException("object is not a Ball");
}