How to add custom sorting for a class with IComparable interface

Sometimes it necessary to sort your collection before showing it on UI.You can add custom sorting to you class just by inheriting it with  IComparable interface.IComparable interface contains one single method CompareTo.

For this post I have created a class Employee which has four properties FirstName,LastName,Age and Title.This class implements IComparable interface,which means instance of the class can be compared with other instance of this class.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Blog_CS
{
    public class Employee : IComparable<Employee>
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Title { get; set; }
    public static List<Employee> Employees
        {
            get
            {
    return new List<Employee>()
                           {
    new Employee(){FirstName = "F004",LastName = "L001",Age = 21,Title = "SE"},
    new Employee(){FirstName = "F002",LastName = "L002",Age = 41,Title = "SSE"},
    new Employee(){FirstName = "F001",LastName = "L003",Age = 21,Title = "JE"},
    new Employee(){FirstName = "F003",LastName = "L003",Age = 31,Title = "APM"},
                           };
            }
        }
    #region IComparable<Employee> Members
    public int CompareTo(Employee other)
        {
    return this.FirstName.CompareTo(other.FirstName);
        }
    #endregion
    }
    class Program
    {
    static void Main(string[] args)
        {
            List<Employee> employees = Employee.Employees;
            employees.Sort();
            Console.WriteLine("FirstName    LastName   Age    Title ");
    foreach (var employee in employees)
            {
    string combineddata = String.Format("{0}\t{1}\t{2}\t", employee.FirstName,
                                employee.LastName, Convert.ToInt32(employee.Age), employee.Title);
                Console.WriteLine(combineddata);
            }
        }
    }
}

No comments:

Post a Comment