IComparable接口示例代码
定义学生类,该类实现IComparable接口的CompareTo方法,该方法对Age 进行大小比较。
public class Student:IComparable{ public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } public int CompareTo(object obj) { Student stu = obj as Student; if (Age > stu.Age) { return 1; } else if (Age == stu.Age) { return 0; } else { return -1; } }}
调用List<T>.Sort方法实现stuList按照学生的年龄来排序。
static void Main(string[] args){ List<Student> stuList = new List<Student>(); stuList.Add(new Student() { Name = "tiana0", Sex = "Man", Age = 18 }); stuList.Add(new Student() { Name = "tiana1", Sex = "Woman", Age = 20 }); stuList.Add(new Student() { Name = "tiana2", Sex = "Woman", Age = 16 }); stuList.Add(new Student() { Name = "tiana3", Sex = "Man", Age = 21 }); stuList.Add(new Student() { Name = "tiana4", Sex = "Woman", Age = 19 }); stuList.Sort(); foreach (Student stu in stuList) { Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age); }}
代码运行结果如下: