2.9 Sort an Array or an ArrayList


2.9 Sort an Array or an ArrayList

Problem

You need to sort the elements contained in an array or an ArrayList .

Solution

Use the ArrayList.Sort method to sort ArrayList objects and the static Array.Sort method to sort arrays.

Discussion

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 typeall 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.)




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net