SoFunction
Updated on 2025-03-08

Analysis of the usage example of Arraylist sort function in C#

This article describes the usage of Arraylist sort function in C#. Share it for your reference. The details are as follows:

There are several commonly used overloads for the sort function of ArrayList:

1. No parameters

2. With one parameter

public virtual void Sort(
  IComparer comparer
)

parameter

comparer

type:

The IComparer implementation to be used when comparing elements.

- or -

The null reference (Nothing in Visual Basic) will use the IComparable implementation of each meta.

Example:

using System;
using ;
public class SamplesArrayList {
  public class myReverserClass : IComparer {
   // Calls  with the parameters reversed.
   int ( Object x, Object y ) {
     return( (new CaseInsensitiveComparer()).Compare( y, x ) );
   }
  }
  public static void Main() {
   // Creates and initializes a new ArrayList.
   ArrayList myAL = new ArrayList();
   ( "The" );
   ( "quick" );
   ( "brown" );
   ( "fox" );
   ( "jumps" );
   ( "over" );
   ( "the" );
   ( "lazy" );
   ( "dog" );
   // Displays the values of the ArrayList.
   ( "The ArrayList initially contains the following values:" );
   PrintIndexAndValues( myAL );
   // Sorts the values of the ArrayList using the default comparer.
   ();
   ( "After sorting with the default comparer:" );
   PrintIndexAndValues( myAL );
   // Sorts the values of the ArrayList using the reverse case-insensitive comparer.
   IComparer myComparer = new myReverserClass();
   ( myComparer );
   ( "After sorting with the reverse case-insensitive comparer:" );
   PrintIndexAndValues( myAL );
  }
  public static void PrintIndexAndValues( IEnumerable myList ) {
   int i = 0;
   foreach ( Object obj in myList )
     ( "\t[{0}]:\t{1}", i++, obj );
   ();
  }
}
/* 
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 
*/

I hope this article will be helpful to everyone's C# programming.