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 Sorting Strings :

Performing a simple sort of text strings that are all the same case, e.g. upper-case, is no more difficult in .NET than it is for sorting integers. The .NET method Array.Sort comes to our rescue by being able to sort objects that are derived from the base System.Array type.

Sorting Strings Alphabetically

This program sorts an array of unsorted strings in to the normal alphabetical order.

Steps

  1. Allocate a small array of text strings that are not yet sorted.
  2. Use the Array.Sort method to sort the array of strings into alphabetical order.
  3. Print the sorted array of text strings to the console.

The Source Code

using System;

class StringSort
{
    static void Main()
    {
        // allocate a small array of ten text strings
        string[] stringValues = { "JUSTIN", "CATHERINE", "AMANDA", "NICHOLAS", "GARETH", "CHRISTOPHER", "PAUL", "ROBERT", "GAIL", "KEVYN" };

        // sort the array in to natural alphabetical order
        Array.Sort(stringValues);

        // output the sorted array
        Console.WriteLine(String.Join(", ", stringValues));
    }
}

Program Output

AMANDA, CATHERINE, CHRISTOPHER, GAIL, GARETH, JUSTIN, KEVYN, NICHOLAS, PAUL, ROBERT

Results

The console output clearly shows that the input array of people’s names, stringValues, has been sorted according to the English alphabet.

Summary

The Array.Sort method is capable of sorting any object in a variety of ways that has been derived from the System.Array base type.

Further Reading

Liked This Post?

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