Multilevel Sorting with IComparable and IComparer: Listing 3.

The CompareTo method.

public int CompareTo(City other)
{
if (String.Compare(this.name, other.name) == 0 &&
    this.population == other.population &&
    RegionCompare(this.region, other.region) == 0)
  return 0;
else if (this.population > other.population)
  return 1;
else if (this.population == other.population &&
  RegionCompare(this.region, other.region) > 0)
  return 1;
else if (this.population == other.population &&
  RegionCompare(this.region, other.region) == 0 &&
  String.Compare(this.name, other.name) > 0)
  return 1;
else
  return -1;
}

About the Author

Dr. James McCaffrey works for Microsoft Research in Redmond, WA. James has worked on several key Microsoft products such as Internet Explorer and Bing. James can be reached at jamccaff@microsoft.com.