C#:Array类的排序

Array类实现了对数组中元素的冒泡排序。Sort()方法需要数组中的元素实现IComparable接口。

  • System.String和System.Int32实现了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             }

输出:

  • 如果对数组使用定制的类,就必须实现IComparable接口(这个接口只定义了一个方法CompareTo(),如果要比较的对象相等,该方法就返回0,如果实例应排在参数对象的前面,该方法就返回小于0的值,反之则返回大于0的值)。
 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排序的姓名):

 

 

posted on 2013-03-06 17:09  LilianChen  阅读(811)  评论(0编辑  收藏  举报

导航