Sunday 13 December 2015

Usage of IComparer , IComparable and IEqualityComparer interfaces

In this post we are going to see the real usage of following interfaces IComparer, IComparable and IEqualityComparer.

IComparer is a interface which is used to sort the Array, this interface will force the class to implement the 
Compare(T x,T y) method, which will compare the two objects. The instance of the class which implemented this interface is used in the sorting of the Array.

IComparable is a interface is implemented in the type which needs to compare the two objects of the same type, This comparable interface will force the class to implement the following method  CompareTo(T obj)

IEqualityComparer is a interface which is used to find the object whether it is Equal or not, Now we will see this in a sample where we have to find the Distinct of a Object in a collection. This interface will implement a method 
Equals(T obj1,T obj2)

Now we take a Example we have a Employee class , based on this class we have to create a Collection. Now we have the following requirements.

1. Sort the Array using Array class
2. Need an collection using Linq : Remove the Duplicate, Order by higher to lower, Remove one employee id

    abstract public class Person
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Address { setget; }
    }

    public enum SortType
    {
        ByID,
        BySalary
    }


IComparer
 public class EmployeeIdSorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Id < y.Id)
                    return 1;
                else if (x.Id > y.Id)
                    return -1;
                else
                    return 0;
            }
        }

        public class EmployeeSalarySorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Salary < y.Salary)
                    return 1;
                else if (x.Salary > y.Salary)
                    return -1;
                else
                    return 0;
            }
        }



IComparable
      public int CompareTo(Employee other)
        {
            if (this.Id < other.Id)
                return 1;
            else if (this.Id > other.Id)
                return -1;
            else
                return 0;
        }


IEqualityComparer
        public class EmployeeDistinctEquality : IEqualityComparer<Employee>
        {
            public EmployeeDistinctEquality()
            {

            }

            public bool Equals(Employee x, Employee y)
            {
                if (x == null && x == null)
                    return true;
                else if (x == null || y == null)
                    return false;
                else if (x.Id == y.Id)
                    return true;
                else
                    return false;
            }

            public int GetHashCode(Employee obj)
            {
                return obj.Id.GetHashCode();
            }
        }


Sorting:
Array.Sort(inputarray, Employee.SorterType(SortType.ByID));
            return inputarray;

Linq :
  IEnumerable<Employee> result = employees.Distinct(Employee.EmpDistinct())
                .OrderByDescending(x => x.Id).Where(x => x.Id != idToRemove);



Full Code :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SAmples
{
    abstract public class Person
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Address { setget; }
    }

    public enum SortType
    {
        ByID,
        BySalary
    }

   
    public class Employee:PersonIComparable<Employee>
    {
        public int Id { getset; }
        public int Salary { setget; }

        public int CompareTo(Employee other)
        {
            if (this.Id < other.Id)
                return 1;
            else if (this.Id > other.Id)
                return -1;
            else
                return 0;
        }

        public static IComparer<Employee> SorterType(SortType type)
        {
            switch (type)
            {
                case SortType.ByID:
                    return new EmployeeIdSorter();
                    
                case SortType.BySalary:
                    return new EmployeeSalarySorter();
                   
                default:
                    return new EmployeeIdSorter();                   
            }
        }

        public static IEqualityComparer<Employee> EmpDistinct()
        {
            return new EmployeeDistinctEquality();
        }

        public class EmployeeIdSorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Id < y.Id)
                    return 1;
                else if (x.Id > y.Id)
                    return -1;
                else
                    return 0;
            }
        }

        public class EmployeeSalarySorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Salary < y.Salary)
                    return 1;
                else if (x.Salary > y.Salary)
                    return -1;
                else
                    return 0;
            }
        }

        public class EmployeeDistinctEquality : IEqualityComparer<Employee>
        {
            public EmployeeDistinctEquality()
            {

            }

            public bool Equals(Employee x, Employee y)
            {
                if (x == null && x == null)
                    return true;
                else if (x == null || y == null)
                    return false;
                else if (x.Id == y.Id)
                    return true;
                else
                    return false;
            }

            public int GetHashCode(Employee obj)
            {
                return obj.Id.GetHashCode();
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();

            Employee[] employees = new Employee[] {
                 new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },
                new Employee() { Id =1,FirstName="Rajesh",LastName="G", Address="Chennai" },
                new Employee() { Id=2,FirstName="Suresh", LastName="G",Address="Chennai" },
               new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },       
              new Employee() { Id=5, FirstName = "Sundar", LastName="S", Address="Madurai" },
                new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },
                new Employee() { Id=4,FirstName="Shiny", LastName="N", Address="US"},
                new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },
            };
         
            int idToRemove = 5;

            IEnumerable<Employee> result = employees.Distinct(Employee.EmpDistinct())
                .OrderByDescending(x => x.Id).Where(x => x.Id != idToRemove);

            Print(result.ToArray());

            Console.WriteLine("\n********************");
            
            Sorting(employees);
            Print(employees);

            Console.Read();


        }

        static void Print(Employee[] result)
        {        
            foreach (Employee emp in result)
                Console.WriteLine(" ID :"+emp.Id+"  Name : "+emp.FirstName);
            
        }

        static Employee[] Sorting(Employee[] inputarray)
        {
            Array.Sort(inputarray, Employee.SorterType(SortType.ByID));
            return inputarray;
        }

    }

   
  

}


Output:




From the output you can see the First print have a distinct collection with sort order using the IComparer, distinct is achieved by using the IEqualitycomparer

From this post you can learn what is the real usage of IComparer, IComparable and IEqualityComparer interfaces.

No comments:

Post a Comment