ProblemYou want to reverse the order of the elements in an array. This might be useful, for instance, immediately after sorting an array to change the sort order from ascending to descending. SolutionSample code folder: Chapter 08\ArrayReversal The Array class provides a shared Reverse() method that reverses the order of its elements. DiscussionThe Array.Reverse() method reverses an array, whether its elements have been sorted first or not. The following code fills a string array with a few fruit names, in no special order. The Array.Reverse() method then reverses the order of the array's elements: Dim result As New System.Text.StringBuilder Dim arrayReverse( ) As String = { _ "Oranges", "Apples", "Grapes", "Bananas", "Blueberries"} ' ----- Show the elements before reversal. result.AppendLine("Before reversing:") For Each fruit As String In arrayReverse result.AppendLine(fruit) Next fruit ' ----- Show the elements after reversal. result.AppendLine( ) result.AppendLine("After reversing:") Array.Reverse(arrayReverse) For Each fruit As String In arrayReverse result.AppendLine(fruit) Next fruit MsgBox(result.ToString( )) The StringBuilder fills first with the strings from the original array, then with the reversed array's contents for comparison. Figure 8-3 shows the results as displayed by the StringBuilder in the message box. Figure 8-3. Reversing the contents of an array with the shared Array.Reverse( ) methodSee AlsoRecipe 8.2 shows another method of arranging the elements of an array. |