C#中Arraylist的sort函数用法实例分析
本文实例讲述了C#中Arraylist的sort函数用法。分享给大家供大家参考。具体如下:
ArrayList的sort函数有几种比较常用的重载:
1.不带参数
2.带一个参数
publicvirtualvoidSort( IComparercomparer )
参数
comparer
类型:System.Collections.IComparer
比较元素时要使用的IComparer实现。
-或-
null引用(VisualBasic中为Nothing)将使用每个元数的IComparable实现。
示例:
usingSystem; usingSystem.Collections; publicclassSamplesArrayList{ publicclassmyReverserClass:IComparer{ //CallsCaseInsensitiveComparer.Comparewiththeparametersreversed. intIComparer.Compare(Objectx,Objecty){ return((newCaseInsensitiveComparer()).Compare(y,x)); } } publicstaticvoidMain(){ //CreatesandinitializesanewArrayList. ArrayListmyAL=newArrayList(); 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"); //DisplaysthevaluesoftheArrayList. Console.WriteLine("TheArrayListinitiallycontainsthefollowingvalues:"); PrintIndexAndValues(myAL); //SortsthevaluesoftheArrayListusingthedefaultcomparer. myAL.Sort(); Console.WriteLine("Aftersortingwiththedefaultcomparer:"); PrintIndexAndValues(myAL); //SortsthevaluesoftheArrayListusingthereversecase-insensitivecomparer. IComparermyComparer=newmyReverserClass(); myAL.Sort(myComparer); Console.WriteLine("Aftersortingwiththereversecase-insensitivecomparer:"); PrintIndexAndValues(myAL); } publicstaticvoidPrintIndexAndValues(IEnumerablemyList){ inti=0; foreach(ObjectobjinmyList) Console.WriteLine("\t[{0}]:\t{1}",i++,obj); Console.WriteLine(); } } /* Thiscodeproducesthefollowingoutput. TheArrayListinitiallycontainsthefollowingvalues: [0]:The [1]:quick [2]:brown [3]:fox [4]:jumps [5]:over [6]:the [7]:lazy [8]:dog Aftersortingwiththedefaultcomparer: [0]:brown [1]:dog [2]:fox [3]:jumps [4]:lazy [5]:over [6]:quick [7]:the [8]:The Aftersortingwiththereversecase-insensitivecomparer: [0]:the [1]:The [2]:quick [3]:over [4]:lazy [5]:jumps [6]:fox [7]:dog [8]:brown */
希望本文所述对大家的C#程序设计有所帮助。