IComparable接口和IComparable<T>接口【实现两个对象之间的比较】 接口将会实现CompareTo(Object obj)和CompareTo(Student student) 代码如下: public int CompareTo(object obj) { throw new NotImplementedException(); } 案例: class Student:IComparable<Student> { public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } //该方法实现年龄的比较 public int CompareTo(Student other) { return this.Age.CompareTo(other.Age); } } class Program { static void Main(string[] args) { Student stu1=new Student(){Name="zhangsan",Age=18,Address="xiangfan"}; Student stu2=new Student(){Name="lisi",Age=20,Address="wuhan"}; int result=stu1.CompareTo(stu2); 结果: 如果result>0 stu1.Age > stu2.Age 如果result=0 stu1.Age = stu2.Age 如果result<0 stu1.Age < stu2.Age } } IComparer接口和IComparer<T>接口【可实现集合对象按照对象的某一个属性进行的排序】 接口将实现Compare(Object x,Object y)、Compare(Student x, Student y) //实现Student类中以年龄进行排序 class ComparerStudentAge:IComparer<Student> { public int Compare(Student x,Student y) { return x.Age.CompareTo(y.Age); } } //实现Student类中以姓名进行排序 class ComparerStudentName:IComparer<Student> { public int Compare(Student x,Student y) { return x.Name.CompareTo(y.Name); } } class Program { static void Main(string[] args) { List<Student> list = new List<Student>() { new Student(){ Name="zhangsan", Age=18, Address="上海浦东"}, new Student(){Name="lisi",Age=20,Address="上海闸北"}, new Student(){Name="wangwu",Age=22,Address="襄樊"}, new Student(){Name="zhaoliu",Age=15,Address="武汉"}, new Student(){Name="qianqi",Age=39,Address="随州"}, new Student(){Name="kunkun",Age=21,Address="襄樊"} }; //使用姓名排序 list.Sort(new ComparerStudentName()); //使用年龄进行排序 list.Sort(New ComparerStudentAge()); } }
C#中实现接口排序
最新推荐文章于 2021-12-12 14:21:14 发布