A For Each loop that iterates in reverse order

A For Each loop that iterates in reverse order

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 FunctionEnd Class

Using the ReverseIterator class is as simple as passing the original collection object to its constructor:

' use an array in this simple testDim arr() As Integer = {1, 2, 3, 4, 5}Dim i As Integer' visit array elements in reverse orderFor Each i In New ReverseIterator(arr)    Console.WriteLine(i)Next

See also  Why ChatGPT Is So Important Today

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist