close
在C# 裡面有提供內建的排序方法,內部使用Quicksort algorithm,這邊介紹三種解法對不同的需求進行排序。
- Primitive types
- Custom types using delegate
- Custom type using ICompareable
Array.Sort()
int,double,string 都能夠輕易地使用Array.Sort(Array)來做排序,因為他們都繼承IComparable interface.
現在來看第一個例子
排序整數
// sort int arrayint[] intArray = new int[5] { 8, 10, 2, 6, 3 }; Array.Sort(intArray); // write array foreach (int i in intArray) Console.Write(i + " "); // output: 2 3 6 8 10
排序字串
// sort string array string [] stringArray = new string[ 5 ] { "Banana" , "Watermelon" , "Tomato" , "Water" , "Apple" }; Array.Sort( stringArray ); // write array foreach ( string str in stringArray) Console .Write ( str + " " ); // output: Apple Banana Tomato Water Watermelon
有時候我們需要排序的不僅只是單一個型態,而是一具有多屬性的物件,並且針對其中一個屬性作排序。
這時候就需要用到 delegate 搭配 anonymous method 來完成,使用Comparison<T>的delegate,定義如下
public delegate int Comparison<T> (T x, T y)
可以看到該泛型Comparesion 傳入兩個相同型態的參數,回傳值為:
<0 : X < Y
0:X = Y
>0 : X > Y
接下來示範排序一個自訂義型態物件的陣列。我們會用到上面提到的匿名委派方法。
定義一個類別具有兩個屬性Name,Height
class Student { public string Name { get ; set ; } public int Height { get ; set ; } }
使用delegate搭配 anonymous method 來進行排序,這裡依照Height屬性由小到大來排序
Student [] studentAry = new Student[]{ new Student { Name = "A1" , Height= 180 }, new Student { Name = "B1" , Height= 170 }, new Student { Name = "C1" , Height= 175 } }; Array.Sort( studentAry , delegate ( Student s1 , Student s2) { return s1.Height.CompareTo(s2 .Height ); }); foreach ( Student str in studentAry) { Console.WriteLine( str. Name + " " + str .Height ); } //B1,C1,A1
- 使用IComparable來排序陣列
延續上一個議題,我們還可以實作IComparable interface來對一個具有多屬性的物件進行排序,當我們實作IComparable後,Sort內部會呼叫IComparable.ComareTo方法,所以我們必續自己去實現裡面的功能。
把原本的Student實作IComparable,實作一個CompareTo方法。
class Student : IComparable { public string Name { get ; set ; } public int Height { get ; set ; } public int CompareTo( object obj ) { if (obj is Student ) { return this.Height.CompareTo ((obj as Student ).Height ); } throw new ArgumentException ("object is not Student" ); } }
而在呼叫端的部分,用法上就跟最初提到的Primitive type 一樣,一行解決!!!
Student [] studentAry = new Student[]{ new Student { Name = "A1" , Height= 180 }, new Student { Name = "B1" , Height= 170 }, new Student { Name = "C1" , Height= 175 } }; Array.Sort( studentAry ); foreach ( Student str in studentAry) { Console .WriteLine ( str. Name + " " + str . Height); } //B1,C1,A1
文章標籤
全站熱搜