CSharp - Array Array Sorting

Introduction

The following illustrates the simplest use of Sort:

int[] numbers = { 3, 2, 1 };
Array.Sort (numbers);                     // Array is now { 1, 2, 3 }

The methods can accept a pair of arrays and rearrange the items of each array in tandem, basing the ordering decisions on the first array.

In the next example, both the numbers and their corresponding words are sorted into numerical order:

int[] numbers = { 3, 2, 1 };
string[] words = { "three", "two", "one" };
Array.Sort (numbers, words);

// numbers array is now { 1, 2, 3 }
// words   array is now { "one", "two", "three" }

Array.Sort requires that the elements in the array implement IComparable.

Comparison delegate follows the same semantics as IComparer<T>.CompareTo:

  • if x comes before y, a negative integer is returned;
  • if x comes after y, a positive integer is returned;
  • if x and y have the same sorting position, 0 is returned.

In the following example, we sort an array of integers such that the odd numbers come first:

Demo

using System;
class MainClass/*www.j av  a2  s .  com*/
{
   public static void Main(string[] args)
   {
         int[] numbers = { 1, 2, 3, 4, 5 };
         Array.Sort (numbers, (x, y) => x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1);

         Array.ForEach (numbers, Console.WriteLine);

   }
}

Result