This examples shows you how to sort or order the values of an array. We can sort it use the Array.Sort() method. Below you'll see a simple example for sorting array of integers and array of strings.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kodecsharp.Example.System
{
class ArraySortDemo
{
public static void Main(string[] args)
{
//
// An array of integer numbers that will be sorted using the
// Array.Sort() method.
//
int[] numbers = { 9, 1, 2, 5, 3, 8, 6, 0, 7 };
Array.Sort(numbers);
//
// Print out the result in order from the smallest to the
// biggest number.
//
foreach (int number in numbers)
{
Console.Write(number);
}
Console.WriteLine();
numbers = new int[] { 9, 1, 2, 5, 3, 8, 6, 0, 7 };
//
// Sort the numbers in the array starting from the fourth
// index up to the four number.
//
Array.Sort(numbers, 4, 4);
foreach (int number in numbers)
{
Console.Write(number);
}
Console.WriteLine();
//
// Sorting an array of string values.
//
string[] colors = {
"white ", "black ", "yellow ",
"green ", "blue ", "red "
};
Array.Sort(colors);
foreach (string color in colors)
{
Console.Write(color);
}
Console.ReadLine();
}
}
}