How do I use the IComparable interface?

后端 未结 6 406
后悔当初
后悔当初 2021-02-02 13:40

I need a basic example of how to use the IComparable interface so that I can sort in ascending or descending order and by different fields of the object type I\'m s

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 14:13

    You can use this for sorting list

    namespace GenaricClass
    {
        class Employee :IComparable
        {
            public string Name { get; set; }
            public double Salary { get; set; }
    
            public int CompareTo(Employee other)
            {
                if (this.Salary < other.Salary) return 1;
                else if (this.Salary > other.Salary) return -1;
                else return 0;
            }
    
            public static void Main()
            {
                List empList = new List()
                {
                    new Employee{Name="a",Salary=140000},
                    new Employee{Name="b",Salary=120000},
                    new Employee{Name="c",Salary=160000},
                    new Employee{Name="d",Salary=10000}
                };
                empList.Sort();
                foreach (Employee emp in empList)
                {
                    System.Console.Write(emp.Salary +",");
                }
                System.Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题