C#中,自定义类型,支持比较和排序,需要实现IComparable接口。IComparable接口存在一个名为CompareTo()的方法,接收类型为object的参数表示被比较对象,返回整型值:1表示当前对象大于被比较对象,0表示两者相等,-1表示当前对象小于被比较对象。
public int CompareTo(object o) {}
若想以更加灵活的方式对自定义类进行比较,可以声明一个继承自IComparer接口的比较器,实现接口方法Comprae(),接收2个object类型参数作为比较对象,返回整型值:1表示前者大于后者,0表示两者相等,-1表示前者小于后者。
public int Compare(object x, object y) {}
IComparable是“可比较的”意思,自定义类实现该接口,就具有可比较的功能;IComparer是“比较器”的意思,实现该接口的类就是一个比较器,可以将比较器“注入”类中,使类具有比较和排序的功能。
IComparable接口示例代码
定义学生类,该类实现IComparable接口的CompareTo方法,该方法对Age 进行大小比较。
1 public class Student : IComparable 2 { 3 public string Name { get; set; } 4 public string Sex { get; set; } 5 public int Age { get; set; } 6 public int CompareTo(object obj) 7 { 8 Student stu = obj as Student; 9 if (Age > stu.Age) 10 { 11 return 1; 12 } 13 else if (Age == stu.Age) 14 { 15 return 0; 16 } 17 else 18 { 19 return -1; 20 } 21 } 22 }
调用List
1 static void Main(string[] args) 2 { 3 ListstuList = new List (); 4 stuList.Add(new Student() { Name = "tiana0", Sex = "Man", Age = 18 }); 5 stuList.Add(new Student() { Name = "tiana1", Sex = "Woman", Age = 20 }); 6 stuList.Add(new Student() { Name = "tiana2", Sex = "Woman", Age = 16 }); 7 stuList.Add(new Student() { Name = "tiana3", Sex = "Man", Age = 21 }); 8 stuList.Add(new Student() { Name = "tiana4", Sex = "Woman", Age = 19 }); 9 stuList.Sort(); 10 foreach (Student stu in stuList) 11 { 12 Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age); 13 } 14 }
IComparer接口示例代码
定义学生类。
public class Student { public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } }
自定义比较器AgeComparer,实现接口IComparer
public class AgeComparer : IComparer{ public int Compare(Student x, Student y) { return x.Age.CompareTo(y.Age); } }
自定义比较器NameComparer,实现接口IComparer
public class NameComparer : IComparer{ public int Compare(Student x, Student y) { return x.Name.CompareTo(y.Name); } }
调用List
1 static void Main(string[] args) 2 { 3 ListstuList = new List (); 4 stuList.Add(new Student() { Name = "aki", Sex = "Man", Age = 18 }); 5 stuList.Add(new Student() { Name = "cki", Sex = "Woman", Age = 20 }); 6 stuList.Add(new Student() { Name = "dki", Sex = "Woman", Age = 16 }); 7 stuList.Add(new Student() { Name = "bki", Sex = "Man", Age = 21 }); 8 stuList.Add(new Student() { Name = "fki", Sex = "Woman", Age = 19 }); 9 stuList.Sort(new AgeComparer()); 10 Console.WriteLine("按照年龄排序:"); 11 foreach (Student stu in stuList) 12 { 13 Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age); 14 } 15 stuList.Sort(new NameComparer()); 16 Console.WriteLine(); 17 Console.WriteLine("按照名称排序:"); 18 foreach (Student stu in stuList) 19 { 20 Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age); 21 } 22 }
原文链接:https://blog.csdn.net/yl2isoft/article/details/13613569