C#:Array類的排序

來源:互聯網
上載者:User

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:IComparable21     {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排序的姓名):

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.