Sorting Arrays
Two useful static methods from Table 10-1 that deserve a closer look are Sort( ) and Reverse( ). These methods do what you think they would: Reverse( ) reverses the order of elements in the array, and Sort( ) sorts the elements in order. These two methods are fully supported for arrays of the built-in C# types, such as string, so sorting an array of strings puts the elements in alphabetical order, and sorting an array of ints puts them in numeric order. Making the Sort( ) method work with your own classes is a bit trickier, because you must implement the IComparable interface (see Chapter 13 for more on interfaces). Example 10-8 demonstrates the use of these two methods to manipulate String objects.
Example 10-8. Array.Sort and Array.Reverse are static methods that let you sort and reverse the contents of an array
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example_10_8_ _ _ _Sorting_and_Reversing_Arrays
{
public class Tester
{
public static void PrintMyArray(string[] theArray)
{
foreach (string str in theArray)
{
Console.WriteLine("Value: {0}", str);
}
Console.WriteLine("\n");
}
static void Main( )
{
String[] myArray =
{
"Proust", "Faulkner", "Mann", "Hugo"
};
PrintMyArray(myArray);
Array.Reverse(myArray);
PrintMyArray(myArray);
String[] myOtherArray =
{
"We", "Hold", "These", "Truths",
"To", "Be", "Self", "Evident",
};
PrintMyArray(myOtherArray);
Array.Sort(myOtherArray);
PrintMyArray(myOtherArray);
}
}
}The output ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access