1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Demo 8 { 9 class Student:IComparable<Student> 10 { 11 12 public Student(int StudentId,string StudentName) 13 { 14 this.StudentId = StudentId; 15 this.StudentName = StudentName; 16 } 17 public string StudentName { get; set; } 18 public int StudentId { get; set; } 19 20 //方法:获取学员信息 21 public string GetStudent() 22 { 23 string info = string.Format("姓名:{0} 学号:{1}",StudentName,StudentId); 24 25 return info; 26 } 27 28 public int CompareTo(Student other) 29 { 30 return other.StudentId.CompareTo(this.StudentId); 31 } 32 } 33 }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #region if运用 namespace Demo { class Program { static void Main(string[] args) { //创建几个学员变量 Student objStu1 = new Student(1001,"小王"); Student objStu2 = new Student(1002,"小张"); Student objStu3 = new Student(1003,"小李"); List<Student> stuList = new List<Student>() {objStu1,objStu2,objStu3 }; stuList.Sort(); foreach (Student stu in stuList) { Console.WriteLine(stu.StudentId+"\t"+stu.StudentName); } Console.ReadLine(); } } } #endregion
如果是对象类型元素,当排序只有一种的时候,可使用默认比较器comparable<T>在类中直接实现接口即可。