Subscribe

RSS Feed (xml)

Sort an Array or an ArrayList

The simplest Sort method overload sorts the objects contained in an array or ArrayList as long as the objects implement the System.IComparable interface and are of the same type—all of the basic data types implement IComparable. The following code excerpt demonstrates how to use the Sort method:
// Create a new array and populate it.
int[] array = {4, 2, 9, 3};

// Sort the array
Array.Sort(array);

// Display the contents of the sorted array 
foreach (int i in array) { Console.WriteLine(i);}

// Create a new ArrayList and populate it.
ArrayList list = new ArrayList(4);
list.Add("Michael");
list.Add("Kate");
list.Add("Andrea");
list.Add("Angus");

// Sort the ArrayList
list.Sort();

// Display the contents of the sorted ArrayList
foreach (string s in list) { Console.WriteLine(s);}
To sort objects that don't implement IComparable, you must pass the Sort method an object that implements the System.Collections.IComparer interface. The IComparer implementation must be capable of comparing the objects contained within the array or ArrayList. (Recipe 16.3 describes how to implement both the IComparable and IComparer interfaces.)

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail