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 your class just by inheriting it with the IComparable interface.IComparable interface contains one single method CompareTo.

I have created a class employee with four properties FirstName, LastName, Age, and Title for this post. This class implements an IComparable interface, which means instances of the class can be compared with other class instances.

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);
            }
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru