C#中实现接口排序 .

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:03   2245   0
  1. IComparable接口和IComparable<T>接口【实现两个对象之间的比较】
  2. 接口将会实现CompareTo(Object obj)和CompareTo(Student student)
  3. 代码如下:
  4. public int CompareTo(object obj)
  5. {
  6. throw new NotImplementedException();
  7. }
  8. 案例:
  9. class Student:IComparable<Student>
  10. {
  11. public string Name { get; set; }
  12. public int Age { get; set; }
  13. public string Address { get; set; }
  14. //该方法实现年龄的比较
  15. public int CompareTo(Student other)
  16. {
  17. return this.Age.CompareTo(other.Age);
  18. }
  19. }
  20. class Program
  21. {
  22. static void Main(string[] args)
  23. {
  24. Student stu1=new Student(){Name="zhangsan",Age=18,Address="xiangfan"};
  25. Student stu2=new Student(){Name="lisi",Age=20,Address="wuhan"};
  26. int result=stu1.CompareTo(stu2);
  27. 结果:
  28. 如果result>0 stu1.Age > stu2.Age
  29. 如果result=0 stu1.Age = stu2.Age
  30. 如果result<0 stu1.Age < stu2.Age
  31. }
  32. }
  33. IComparer接口和IComparer<T>接口【可实现集合对象按照对象的某一个属性进行的排序】
  34. 接口将实现Compare(Object x,Object y)、Compare(Student x, Student y)
  35. //实现Student类中以年龄进行排序
  36. class ComparerStudentAge:IComparer<Student>
  37. {
  38. public int Compare(Student x,Student y)
  39. {
  40. return x.Age.CompareTo(y.Age);
  41. }
  42. }
  43. //实现Student类中以姓名进行排序
  44. class ComparerStudentName:IComparer<Student>
  45. {
  46. public int Compare(Student x,Student y)
  47. {
  48. return x.Name.CompareTo(y.Name);
  49. }
  50. }
  51. class Program
  52. {
  53. static void Main(string[] args)
  54. {
  55. List<Student> list = new List<Student>()
  56. {
  57. new Student(){ Name="zhangsan", Age=18, Address="上海浦东"},
  58. new Student(){Name="lisi",Age=20,Address="上海闸北"},
  59. new Student(){Name="wangwu",Age=22,Address="襄樊"},
  60. new Student(){Name="zhaoliu",Age=15,Address="武汉"},
  61. new Student(){Name="qianqi",Age=39,Address="随州"},
  62. new Student(){Name="kunkun",Age=21,Address="襄樊"}
  63. };
  64. //使用姓名排序
  65. list.Sort(new ComparerStudentName());
  66. //使用年龄进行排序
  67. list.Sort(New ComparerStudentAge());
  68. }
  69. }
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP