Sort an array

The following illustrates the simplest use of Sort:


using System;
using System.Collections;

class Sample
{
    public static void Main()
    {
        int[] numbers = { 3, 2, 1 };
        Array.Sort(numbers);  // Array is now { 1, 2, 3 }

        Array.ForEach(numbers, Console.WriteLine);
    }

}

The output:


1
2
3

Array.ForEach can work with two arrays as well. It takes 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:


using System;
using System.Collections;

class Sample
{
    public static void Main()
    {
        int[] numbers = { 3, 2, 1 };
        string[] words = { "three", "two", "one" }; 
        Array.Sort(numbers, words);
        Array.ForEach(numbers, Console.WriteLine);
        Array.ForEach(words, Console.WriteLine);

    }

}

The output:


1
2
3
one
two
three
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.