C# ArrayList Sort(IComparer)

Description

ArrayList Sort(IComparer) sorts the elements in the entire ArrayList using the specified comparer.

Syntax

ArrayList.Sort(IComparer) has the following syntax.


public virtual void Sort(
  IComparer comparer
)

Parameters

ArrayList.Sort(IComparer) has the following parameters.

  • comparer - The IComparer implementation to use when comparing elements.
  • comparer - -or-
  • comparer - A null reference (Nothing in Visual Basic) to use the IComparable implementation of each element.

Returns

ArrayList.Sort(IComparer) method returns

Example

The following code example shows how to sort the values in an ArrayList using the default comparer and a custom comparer that reverses the sort order.


using System;/*w w w . j a v  a  2s  .co  m*/
using System.Collections;

public class SamplesArrayList  {

   public class myReverserClass : IComparer  {
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

   }

   public static void Main()  {
      ArrayList myAL = new ArrayList();
      myAL.Add( "A" );
      myAL.Add( "B" );
      myAL.Add( "C" );
      myAL.Add( "1" );
      myAL.Add( "2" );
      myAL.Add( "3" );
      myAL.Add( "X" );
      myAL.Add( "Y" );
      myAL.Add( "Z" );

      IComparer myComparer = new myReverserClass();
      myAL.Sort( myComparer );

      foreach ( Object obj in myAL )
         Console.WriteLine(obj );
   }

}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections »




ArrayList
BitArray
Comparer
Hashtable
Queue
SortedList
Stack