We use Sort() method for sorting an arraylist. And once sorted, arraylist can be searched by BinarySearch().
Following example demonstrates these functionality
private void SortAndSearchArrayList() { string OriginalStr=""; string AfterSortingStr=""; ArrayList ArrList = new ArrayList(); ArrList.Add(21); ArrList.Add(30); ArrList.Add(25); ArrList.Add(22); ArrList.Add(20); ArrList.Add(35); ArrList.Add(24); foreach(int i in ArrList) { OriginalStr = OriginalStr + i + " "; } //Sort ArrList.Sort(); foreach (int i in ArrList) { AfterSortingStr = AfterSortingStr + i + " "; } //Searching-suppose you want to find out th eindex of 22 MessageBox.Show("Index of 22 is " + ArrList.BinarySearch(22)); }
value of OriginalStr = 21 30 25 22 20 35 24
value of AfterSortingStr = 20 21 22 24 25 30 35
Although An arraylist can contains objects of any type within the same list, when sorting and searching a list , it is very important for those objects to be comparable. for example above program would have generated an exception if the list had included a string.