ArrayList.Sort()解析

ArrayList的sort函数有几种比较常用的重载:

1.不带参数

2.带一个参数

 

public virtual void Sort(
	IComparer comparer
)
参数
comparer
类型: System.Collections.IComparer 比较元素时要使用的 IComparer 实现。 - 或 - null 引用(Visual Basic 中为 Nothing)将使用每个元数的 IComparable 实现。
example:
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 
*/

转载于:https://www.cnblogs.com/ZLGBloge/p/4119021.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值