Wednesday, July 31, 2013

C#: IComparer vs IComparable

In sorting a list of objects, I encountered these interfaces(IComparer and IComparable). These two interfaces define the logic for sorting.



using System.Collections.Generic;

class CompareByAge : IComparer<Employee>
{
    public int Compare(Employee a, Employee b)
    {
        if(a.Age > b.Age) return 1;
        else if(a.Age < b.Age) return -1;
        else return 0;
    }
}
Employees.Sort(new CompareByAge()); //sorts employees based on their age in ascending order


class Location : IComparable<Location>
{
    private
int population;
    private string country;
   
    public
int Population
    {
        get { return population; }
        set { population = value; }
    }
   
    public string Country
    {
        get { return country; }
        set { country = value; }
    }
   
    public Location()
    {
        population = 0;
        country = 0;
    }
   
    public
int CompareTo(Location other)
    {
        if(this.Population == other.Population) return this.Country.CompareTo(other.Country);
        else return other.Population.CompareTo(this.Population);
    }
}
Locations.Sort(); //sorts countries based on population in ascending order. for same population, they are sorted by their country names

No comments:

Post a Comment