Custom Sorting

How list know to sorting the data inside? How if we want to sort the list with our own rules?

We have to use other methods called IComparer and IComparable.

  • IComparer as I'm comparer, I simply compare which means I compare two instances.
  • IComparable as I'm comparable. I can be compared to another instance of the same type.

IComparable


public class Person : IComparable
{
    // private fields
    private string _FirstName;
    private string _LastName;
    private int _Age;

    public Person() { }

    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }

    //Properties
    public string FirstName { get; set }

    public string LastName { get; set }

    public int Age { get; set }

    //This was the interface member
    public int CompareTo(object obj)
    {
        Person Temp = (Person)obj;
        if (this.Age < Temp.Age)
            return 1;
        if (this.Age > Temp.Age)
            return -1;
        else
            return 0;
    }
}
class Program
{
    public static void Main(string[] args)
    {
        // TODO: Implement Functionality Here
        Person me = new Person("Bejaoui", "Bechir", 29);
        Person myFather = new Person("Bejaoui", "Massinissa", 65);
        int state = me.CompareTo(myFather);
        if (state == 1) Console.WriteLine("My father is older than me");
        if (state == -1) Console.WriteLine("I'm older than my father!!!");
        if (state == 0) Console.WriteLine("My Father and I have the same age!");
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

IComparer

public class CompareByName : IComparer
{
    public CompareByName() { }
    //Implementing the Compare method

    public int Compare(object object1, object object2)
    {
        Person Temp1 = (Person)object1;
        Person Temp2 = (Person)object2;
        return string.Compare(Temp1.FirstName, Temp2.FirstName);
    }
}
var people = new Person[] { new Person(){"Bejaoui", "Bechir", 29}, new Person(){"Bejaoui", "Massinissa", 65} };
people.Sort(new CompareByName()); //peole will be sorted by FirstName.

results matching ""

    No results matching ""