- 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)
-
-
-
- class ComparerStudentAge:IComparer<Student>
- {
- public int Compare(Student x,Student y)
- {
- return x.Age.CompareTo(y.Age);
- }
- }
-
-
- 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());
- }
- }
|
|