Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
Problem
You 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. Solution
Sample code folder: Chapter 08\ArrayReversal The Array class provides a shared Reverse() method that reverses the order of its elements. Discussion
The 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( ) method
See Also
Recipe 8.2 shows another method of arranging the elements of an array. |
Категории