The For Each loop always iterates orderly on all the elements of an array or a collection (more precisely, on all the elements of a class that implements the IEnumerable interface). What happens if you need to iterate in reverse order, though? If you have an array or an ArrayList you can always reference items by their numerical index, but not all the collection objects give you this ability (for example, you can't access Dictionary items by an index). The following class works as a wrapper for any IEnumerable class and lets you visit all its items in reverse order:
Class ReverseIterator
Implements IEnumerable
' a low-overhead ArrayList to store references
Dim items As New ArrayList()
Sub New(ByVal collection As IEnumerable)
' load all the items in the ArrayList, but in reverse order
Dim o As Object
For Each o In collection
items.Insert(0, o)
Next
End Sub
Public Function GetEnumerator() As System.Collections.IEnumerator _
Implements System.Collections.IEnumerable.GetEnumerator
' return the enumerator of the inner ArrayList
Return items.GetEnumerator()
End Function
End Class
Using the ReverseIterator class is as simple as passing the original collection object to its constructor:
' use an array in this simple test
Dim arr() As Integer = {1, 2, 3, 4, 5}
Dim i As Integer
' visit array elements in reverse order
For Each i In New ReverseIterator(arr)
Console.WriteLine(i)
Next