在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Array类实现了对数组中元素的冒泡排序。Sort()方法需要数组中的元素实现IComparable接口。
1 string[] names = { "Mike Lissick", "Mark Allen", "John Dixon", "Greg" }; 2 Array.Sort(names); 3 foreach (string name in names) 4 { 5 Console.WriteLine(name); 6 Console.ReadLine(); 7 } 输出:
1 using System; 2 3 namespace ConsoleApplication4 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Person[] beatles = { new Person("Mike", "Lissick"), new Person("Mark", "Allen"), new Person("John", "Dixon") }; 10 Person[] beatlesClone = (Person[])beatles.Clone(); 11 Array.Sort(beatles); 12 foreach (Person p in beatles) 13 { 14 Console.WriteLine(p); 15 Console.ReadLine(); 16 } 17 } 18 } 19 20 public class Person:IComparable 21 { 22 public int CompareTo(object obj) 23 { 24 Person other = obj as Person; 25 int result = this.LastName.CompareTo(other.LastName); 26 if (result == 0) 27 { 28 result = this.FirstName.CompareTo(other.FirstName); 29 } 30 return result; 31 } 32 33 public Person() 34 { } 35 36 public Person(string firstName, string lastName) 37 { 38 this.FirstName = firstName; 39 LastName = lastName; 40 } 41 42 public string FirstName { get; set; } 43 public string LastName { get; set; } 44 public override string ToString() 45 { 46 return String.Format("{0} {1}", FirstName, LastName); 47 } 48 } 49 } 输出(按照Lastname排序的姓名):
|
请发表评论