Sorting
The Array class implements a bubble – sort for sorting the elements in the array. The Sort() method requires
the interface IComparable to be implemented by the elements in the array. Simple types such as System.
String and System.Int32 implement IComparable , so you can sort elements containing these types.
With the sample program, the array name contains elements of type string, and this array can be sorted:
string[] names = {
“Christina Aguilera”,
“Shakira”,
“Beyonce”,
“Gwen Stefani”
};
Array.Sort(names);
foreach (string name in names)
{
Console.WriteLine(name);
}
The output of the application shows the sorted result of the array:
Beyonce
Christina Aguilera
Gwen Stefani
Shakira
If you are using custom classes with the array, you must implement the interface IComparable . This
interface defines just one method, CompareTo() , that must return 0 if the objects to compare are equal, a
value smaller than 0 if the instance should go before the object from the parameter, and a value larger
than 0 if the instance should go after the object from the parameter.
Advertisements