CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Friday, May 01, 2009

Sorting a collection using IComparer

Place this code in the collection.

public class EmployeeList

{

       public void Sort()
       {
           base.InnerList.Sort(new DateComparer());
       }

}

Create “DateComparer” class which implements IComparer and provides methods to compare to objects. This Compare method compares the joining dates of the employees and sorts the list.

/// <summary>
    /// This is for Joiningdate comparision
    /// </summary>
    public class DateComparer : IComparer
    {
        /// <summary>
        /// This method compares Joiningdate
        /// </summary>
        /// <returns>int</returns>
        public int Compare(object LobjEmployeeFirst, object LobjEmployeeSecond)
        {
return -((Employee)LobjEmployeeFirst).JoiningDate.CompareTo(((Employee)LobjEmployeeSecond).JoiningDate);

        }
    }

Post a Comment