Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

A For Each loop that iterates in reverse order

Total Hit ( 11881)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


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:

Click here to copy the following block
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:

Click here to copy the following block
' 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


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.