C#中Arraylist的sort函數用法實例剖析。本站提示廣大學習愛好者:(C#中Arraylist的sort函數用法實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中Arraylist的sort函數用法實例剖析正文
本文實例講述了C#中Arraylist的sort函數用法。分享給年夜家供年夜家參考。詳細以下:
ArrayList的sort函數有幾種比擬經常使用的重載:
1.不帶參數
2.帶一個參數
public virtual void Sort( IComparer comparer )
參數
comparer
類型:System.Collections.IComparer
比擬元素時要應用的 IComparer 完成。
- 或 -
null 援用(Visual Basic 中為 Nothing)將應用每一個元數的 IComparable 完成。
示例:
using System; using System.Collections; public class SamplesArrayList { public class myReverserClass : IComparer { // Calls CaseInsensitiveComparer.Compare with the parameters reversed. int IComparer.Compare( Object x, Object y ) { return( (new CaseInsensitiveComparer()).Compare( y, x ) ); } } public static void Main() { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add( "The" ); myAL.Add( "quick" ); myAL.Add( "brown" ); myAL.Add( "fox" ); myAL.Add( "jumps" ); myAL.Add( "over" ); myAL.Add( "the" ); myAL.Add( "lazy" ); myAL.Add( "dog" ); // Displays the values of the ArrayList. Console.WriteLine( "The ArrayList initially contains the following values:" ); PrintIndexAndValues( myAL ); // Sorts the values of the ArrayList using the default comparer. myAL.Sort(); Console.WriteLine( "After sorting with the default comparer:" ); PrintIndexAndValues( myAL ); // Sorts the values of the ArrayList using the reverse case-insensitive comparer. IComparer myComparer = new myReverserClass(); myAL.Sort( myComparer ); Console.WriteLine( "After sorting with the reverse case-insensitive comparer:" ); PrintIndexAndValues( myAL ); } public static void PrintIndexAndValues( IEnumerable myList ) { int i = 0; foreach ( Object obj in myList ) Console.WriteLine( "\t[{0}]:\t{1}", i++, obj ); Console.WriteLine(); } } /* This code produces the following output. The ArrayList initially contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After sorting with the default comparer: [0]: brown [1]: dog [2]: fox [3]: jumps [4]: lazy [5]: over [6]: quick [7]: the [8]: The After sorting with the reverse case-insensitive comparer: [0]: the [1]: The [2]: quick [3]: over [4]: lazy [5]: jumps [6]: fox [7]: dog [8]: brown */
願望本文所述對年夜家的C#法式設計有所贊助。