Pages

Friday, December 10, 2010

DotNet - IComparer Interface

What is IComparer?

Its an interface which Exposes a method that compares two objects.This interface is used in conjunction with the Collection.Sort and Array.BinarySearch methods. It provides a way to customize the sort order of a collection. This interface has a method 'Compare' which Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.

Basicaly this interface uses for sorting the collection of custome object by one of their property.


Example : For soting a collection.

public class GenericComparer : IComparer
{
    private String _Property = null;
    private SortOrderEnum _SortOrder = SortOrderEnum.Ascending;
   
    public String SortProperty
    {
        get { return _Property; }
        set { _Property = value; }
    }

    public SortOrderEnum SortOrder
    {
        get { return _SortOrder; }
        set { _SortOrder = value; }
    }

    public int Compare(object x, object y)
    {
        Fruit ing1;
        Fruit ing2;
       
        if (x is Fruit)
            ing1 = (Fruit) x;
        else
            throw new ArgumentException("Object is not of type Fruit");

        if (y is Fruit)
            ing2 = (Fruit) y;
        else
            throw new ArgumentException("Object is not of type Fruit");
       
        if (this.SortOrder.Equals(SortOrderEnum.Ascending))
            return ing1.CompareTo(ing2, this.SortProperty);
        else
            return ing2.CompareTo(ing1, this.SortProperty);
    }
}


The sort order enumeration.

public enum SortOrderEnum
{
    Ascending,
    Descending
}

Now we can use this comparer in our sort method like

public void Sort(String SortBy, SortOrderEnum SortOrder)
{
    GenericComparer comparer = new GenericComparer();
    comparer.SortProperty = SortBy;
    comparer.SortOrder = SortOrder;
    this.InnerList.Sort(comparer);
}

Reference :

http://www.codeproject.com/KB/cs/GenericComparer.aspx

No comments:

Post a Comment