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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS