1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 数组排序 8 { 9 /// <summary> 10 /// IComparable : 接口 11 /// </summary> 12 public class Student : IComparable 13 { 14 public int ID { get; set; } 15 public string Name { get; set; } 16 public int Age { get; set; } 17 18 /// <summary> 19 /// 重写ToString方法 20 /// </summary> 21 /// <returns></returns> 22 public override string ToString() 23 { 24 return String.Format("ID={0} Name={1} Age={2}", this.ID, this.Name, this.Age); 25 } 26 27 /// <summary> 28 /// 实现IComparable接口的CompareTo()方法来通过【Age】来进行排序 29 /// </summary> 30 /// <param name="obj"></param> 31 /// <returns>1:大于 -1:小于 0:等于</returns> 32 public int CompareTo(object obj) 33 { 34 Student student = (Student)obj; 35 if ( this.Age > student.Age) 36 { 37 return 1; 38 } 39 if (this.Age < student.Age) 40 { 41 return -1; 42 } 43 return 0; 44 } 45 } 46 47 class Program 48 { 49 static void Main(string[] args) 50 { 51 Student[] student = 52 { 53 new Student(){ID = 001, Name = "张三", Age = 15}, 54 new Student(){ID = 002, Name = "李四", Age = 16}, 55 new Student(){ID = 003, Name = "王五", Age = 18}, 56 new Student(){ID = 004, Name = "赵六", Age = 14} 57 }; 58 59 //Console.WriteLine(student); // 打印结果: 数组排序.Student[] 60 //Console.WriteLine(student[1]); // 打印结果: ID=002, Name="李四", Age=16 61 62 Console.WriteLine("student数组未进行排序前:"); 63 for (int i = 0; i < student.Length; ++i ) 64 { 65 Console.WriteLine("student[{0}] : {1}", i, student[i]); 66 } 67 68 /// Array.Sort():数组的静态方法:默认升序排列 69 Array.Sort(student); 70 Console.WriteLine(" =================按照【Age】升序排序后==================="); 71 foreach (var v in student) 72 { 73 Console.WriteLine(v); //默认调用Student的ToString()方法 74 } 75 76 /// Array.Reverse()方法:反转整个一维数组的元素顺序 77 /// 如果要实现【降序】排列,则必须先通过Array.Sort(数组)的方法先将数组按升序有序排列后,再 78 /// 调用Array.Reverse()方法反转数组的元素,实现降序排列. 79 /// 如果要实现自定义类型的数组排序,则必须要 80 Array.Reverse(student); 81 Console.WriteLine(" =================按照【Age】降序排序后==================="); 82 foreach (Student st in student) 83 { 84 Console.WriteLine(st); 85 } 86 87 Console.ReadLine(); 88 } 89 } 90 }