一、如果是基本数据类型元素,可以直接排序;
1 //创建一个泛型集合并初始化;2 ListnameList = new List () { "3小明", "1小王", "2小林", "5小周", "4小郭" };3 //基本数据类型,直接调用sort()实现排序;4 nameList.Sort();5 Console.WriteLine("=====初始状态======");6 foreach (var item in nameList)7 {8 Console.WriteLine(item);9 }
二、如果是对象类型元素
1、当排序只有一种的时候,可以使用默认比较器IComparable<T>在类中直接实现接口即可;
当对集合对象进行排序的时候,需要使用接口来实现默认排序;
1 class Student:IComparable//默认的排序,只能有一种 2 { 3 public Student()//无参数构造函数 4 { 5 6 } 7 public Student(int stuId,string stuName)//带两个参数的构造函数 8 { 9 this.StudentId = stuId;10 this.StudentName = stuName;11 }12 public int StudentId { get; set; }13 public string StudentName { get; set; }14 public int Age { get; set; }15 16 public int CompareTo(Student other)17 {18 return other.StudentId.CompareTo(this.StudentId);19 //this 在前,other在后是升序,反之降序20 21 }22 }
最终在使用时候直接调用sort()来实现排序,编译器直接调用接口实现类;
1 //创建几个学员对象 2 Student objStudent1 = new Student(1001, "小明"); 3 Student objStudent2 = new Student(1002, "小王"); 4 Student objStudent3 = new Student(1003, "小林"); 5 Student objStudent4 = new Student(1004, "小周"); 6 Student objStudent5 = new Student(1005, "小郭"); 7 ListobjStu = new List () { objStudent3 , objStudent5 , objStudent1 , objStudent4 , objStudent2 }; 8 Console.WriteLine("=====对象排序前======="); 9 foreach (var item in objStu)10 {11 Console.WriteLine(item.StudentId+"\t"+item.StudentName);12 }13 //默认排序14 objStu.Sort();15 Console.WriteLine("=====对象默认排序后=======");16 foreach (var item in objStu)17 {18 Console.WriteLine(item.StudentId + "\t" + item.StudentName);19 }20 Console.ReadLine();
2、当需要多种排序的时候,需要田间对应排序类,并给每个排序类实现比较器接口ICompare<T>来完成不同的排序方法;
首先在对象类中,实现是个排序类接口:
1 //添加四个排序类,需要几种排序,就添加几个排序类;并且分别实现排序比较接口,实现动态排序 2 #region 四个排序类 3 class StuNameAsc : IComparer4 { 5 public int Compare(Student x, Student y) 6 { 7 return x.StudentName.CompareTo(y.StudentName); 8 } 9 }10 class StuNameDesc : IComparer 11 {12 public int Compare(Student x, Student y)13 {14 return y.StudentName.CompareTo(x.StudentName);15 }16 }17 class AgeAsc : IComparer 18 {19 public int Compare(Student x, Student y)20 {21 return x.Age.CompareTo(y.Age);22 }23 }24 class AgeDesc : IComparer 25 {26 public int Compare(Student x, Student y)27 {28 return y.Age.CompareTo(x.Age);29 }30 }31 #endregion
接下来在实际调用当中,会根据你的对象类调用实现:
1 //创建几个学员对象 2 Student objStudent1 = new Student(1001, "小明"); 3 Student objStudent2 = new Student(1002, "小王"); 4 Student objStudent3 = new Student(1003, "小林"); 5 Student objStudent4 = new Student(1004, "小周"); 6 Student objStudent5 = new Student(1005, "小郭"); 7 ListobjStu = new List () { objStudent3 , objStudent5 , objStudent1 , objStudent4 , objStudent2 }; 8 Console.WriteLine("=====对象排序前======="); 9 foreach (var item in objStu)10 {11 Console.WriteLine(item.StudentId+"\t"+item.StudentName);12 }13 Console.WriteLine("======按姓名升序排序===========");14 objStu.Sort(new StuNameAsc()); //传递接口实现类来实现排序15 //排序输出结果16 foreach (var item in objStu)17 {18 Console.WriteLine(item.StudentId + "\t" + item.StudentName);19 }20 21 Console.ReadLine();