C# Array Sort(Array, IComparer)

Description

Array Sort(Array, IComparer) sorts the elements in a one-dimensional Array using the specified IComparer.

Syntax

Array.Sort(Array, IComparer) has the following syntax.


public static void Sort(
  Array array,
  IComparer comparer
)

Parameters

Array.Sort(Array, IComparer) has the following parameters.

  • array - The one-dimensional Array to sort.
  • comparer - The IComparer implementation to use when comparing elements.
  • comparer - -or-
  • comparer - null to use the IComparable implementation of each element.

Returns

Array.Sort(Array, IComparer) method returns

Example

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


//  w w  w  .  j ava 2s . c o  m
using System;
using System.Collections;

class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed. 
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

}
   
public class SamplesArray  {
   public static void Main()  {

      String[] myArr = { "A", "C", "X", "Y", "A", "O", "W", "Q", "X" };
      IComparer myComparer = new myReverserClass();

      Array.Sort( myArr, 1, 3 );
      Array.Sort( myArr, 1, 3, myComparer );
      Array.Sort( myArr );
      Array.Sort( myArr, myComparer );
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version