Site Search
Homepage of Otaku No Zoku
Complete Archives of Otaku No Zoku
About Otaku No Zoku
Subscribe to Otaku No Zoku
Bookmark Otaku No Zoku

C# Array.Sort Example :

Sorting arrays in .NET is trivially easy. The Array.Sort method is very simple to use and one of the fastest implementations for doing a straight forward sort that you can make use of. For most of your array sorting requirements, this is the function you should be using.

Sorting Of An Array

This program sorts a small array of unsorted integers, placing them in to their natural numerical order.

Steps

  1. Allocate a small array of integers that are not yet sorted.
  2. Use the Array.Sort method to sort the array of integers in to numerical order.
  3. Print the sorted array of integers to the console.

The Source Code

using System;

class ArraySort
{
    static void Main()
    {
        // allocate a small array of ten integers
        int[] numericalValues = { 43, 7, 19, 99, 57, 25, 45, 12, 37, 28 };

        // sort the array in to natural numerical order
        Array.Sort(numericalValues);

        // output each number in the array
        Console.WriteLine(String.Join(", ", numericalValues));
    }
}

Program Output

7, 12, 19, 25, 28, 37, 43, 45, 57, 99

Results

Taking a look at the output you can clearly see that the input array, numericValues, containing ten distinct integers in no particular order, has been sorted successfully.

Summary

The method Array.Sort has 17 overloads as of .NET 4.0 offering the ability to sort not just plain numeric arrays but all kinds of data and in a variety of differing ways.

Further Reading

Liked This Post?

Subscribe to the RSS feed or follow me on Twitter to stay up to date!