SoFunction
Updated on 2025-03-07

Deeply explain the sorting examples of IComparable and IComparer


using System;
using ;
using ;
using ;
namespace hgoApp
{
    class Comparer
    {
        static void Main()
        {
            Employee[] Employees = new Employee[5];

Employees[0] = new Employee("Zhang San", 2800);
Employees[1] = new Employee("Li Si", 1800);
Employees[2] = new Employee("Wang Wu", 5800);
Employees[3] = new Employee("Maliu", 12800);
Employees[4] = new Employee("Qian Qi", 8800);
("Sort by name");
            (Employees);
            foreach (Employee em in Employees)
            {
                (em);
            }
("Sorted by salary");
            (Employees, );
            foreach (Employee em in Employees)
            {
                (em);
            }
        }
    }
    class Employee : IComparable
    {
        private string _Name;
        public string Name
        {
            get { return _Name; }
        }
        private int _Salary;
        public int Salary
        {
            get { return _Salary; }
        }
        public Employee(string Name, int Salary)
        {
            _Name = Name;
            _Salary = Salary;
        }
//Display interface implementation
        int (object obj)
        {
            if (!(obj is Employee))
            {
throw new ArgumentException("not Employee class");
            }
            return _Name.CompareTo(((Employee)obj)._Name);
        }
//Providing a common strongly typed overloaded version
        public int CompareTo(Employee Em)
        {
            return _Name.CompareTo(Em._Name);
        }
//When the Employee is instantiated for the first time, _SalaryCom is empty. When using SalaryCom, a SalaryCompare object will be created. The second or third times, you can use _SalaryCom directly.
        private static SalaryCompare _SalaryCom = null;
        public static IComparer SalaryCom
        {
            get
            {
                if (_SalaryCom == null)
                {
                    _SalaryCom = new SalaryCompare();
                }
                return _SalaryCom;
            }
        }
//Nested class (this class is a class that sorts for salary)
        private class SalaryCompare:IComparer
        {
//Sort elements in Array using the specified IComparer
            int (object obj1,object obj2)
            {
                if (!(obj1 is Employee) || !(obj2 is Employee))
                {
throw new ArgumentException("not Employee class");
                }
                return ((Employee)obj1)._Salary.CompareTo(((Employee)obj2)._Salary);
            }
        }
        public override string ToString()
        {
            return _Name +"  "+ _Salary.ToString();
        }
    }
}