C#----用实例来理解IComparable和IComparer

来源:互联网 发布:淘宝交易资金冻结多久 编辑:程序博客网 时间:2024/04/29 15:58

C#中的基本类型都提供了默认的比较算法,C#可以调用比较算法为基本类型的数组进行排序。

若希望对自建类进行比较或排序,那么可以使用IComparable<T>和IComparer<T>接口。

一、IComparable<T>接口

继承IComparable<T>接口,可以给自建类实现一个通用的比较方法,使自建类的数组可以使用Array. Sort方法进行排序。

实现IComparable<T>接口,要求在类中实现CompareTo方法,该方法参数是一个T类型的对象,返回值必须是-1,0,1中之一。

例子如下:

public class Student : IComparable<Student>    {        private string firstName;        private string lastName;        private int  englishScore;        private int  chineseScore;        public Student(string firstName, string lastName, int englishScore, int chineseScore)        {            this.firstName = firstName;            this.lastName = lastName;            this.englishScore = englishScore;            this.chineseScore = chineseScore;        }        public string FirstName        {            get { return firstName; }            set { firstName = value; }        }        public string LastName        {            get { return lastName; }            set { lastName = value; }        }        public int EnglishScore        {            get { return englishScore; }            set { englishScore = value; }        }        public int ChineseScore        {            get { return chineseScore; }            set { chineseScore = value; }        }        public int CompareTo(Student other)        {            if (other == null) throw new ArgumentNullException("other");            int result = string.Compare(this.firstName,other.firstName);            if (result == 0)            {                result = string.Compare(this.lastName, other.lastName);            }            return result;           }    }    class Program    {        static void Main(string[] args)        {            Student[] students = new[] { new Student("dan", "Li", 10, 30), new Student("hua", "Li", 20, 40), new Student("chang", "shu", 40, 50) };            Array.Sort(students);            foreach(Student student in students)            {                Console.WriteLine(student.FirstName + " " + student.LastName + " English:" + student.EnglishScore + " Chinese:" + student.ChineseScore);                }            Console.Read();        }    }
输出结果是:

可以看到,4个学生的信息被按照名字顺序排序。

二、IComparer<T>接口

IComparer<T>可以提供了CompareTo方法,并且可以接受参数,以用户需要的比较类型排序。

例子中的StudentComparer类提供了两种不同的为Student数组排序的方法:

public classStudent

    {

        private string firstName;

        private string lastName;

        private int englishScore;

        private int chineseScore;

        public Student(string firstName,string lastName, int englishScore, int chineseScore)

        {

            this.firstName =firstName;

            this.lastName =lastName;

            this.englishScore =englishScore;

            this.chineseScore =chineseScore;

        }

 

        public string FirstName

        {

            get { return firstName; }

            set { firstName = value; }

        }

 

        public string LastName

        {

            get { return lastName; }

            set { lastName = value; }

        }

 

        public int EnglishScore

        {

            get { return englishScore; }

            set { englishScore = value; }

        }

        public int ChineseScore

        {

            get { return chineseScore; }

            set { chineseScore = value; }

        }

 

    }

    public enum StudentCompareType

    {

        ChineseScore,

        EnglishScore

    }

 

    public class StudentComparer : IComparer<Student>

    {

        private StudentCompareType compareType;

 

        public StudentComparer(StudentCompareTypecompareType)

        {

            this.compareType =compareType;

        }

 

        public int Compare(Studentx, Studenty)

        {

            int result;

            switch (compareType)

            {

                case StudentCompareType.ChineseScore:

                   result = x.ChineseScore.CompareTo(y.ChineseScore);

                   break;

                case StudentCompareType.EnglishScore:

                   result = x.EnglishScore.CompareTo(y.EnglishScore);

                   break;

                default:

                       throw new ArgumentException("unexpected compare type");

                   break;

            }

            return result;

        }

 

    }

 

    class Program

    {

 

        static void Main(string[]args)

        {

 

            Student[] students = new[] { new Student("dan","Li", 10, 30), new Student("hua","Li", 20, 40), new Student("chang","shu", 40, 50) };

            Array.Sort(students,newStudentComparer(StudentCompareType.ChineseScore));

 

            foreach(Studentstudent in students)

            {

                Console.WriteLine(student.FirstName +" " + student.LastName +"English:" + student.EnglishScore +" Chinese:" + student.ChineseScore);   

            }

            Console.Read();

        }

输出结果是:




原创粉丝点击