1

I have set up a For Each statement that loops through a list. The list is made up of 'pixels' which is a custom picturebox class. I need to setup a loop that goes through the list in reverse order. This is what my normal loop looks like:

        For Each Tile As Pixel In PixelList
            If Tile.PixelNumber = 1 Then
                Tile.NewColour()
            End If
        Next

PixelNumber is just a integer variable that keeps count of which pixel is which.

Pixel is the custom Picturebox class

PixelList is the name of the list

I need to be able to setup a similar loop but one that goes through the list in reverse order of when I Tile was added. So a first in first out situation.

Cesare
  • 71
  • 9
  • 2
    `For i As Integer = PixelList.Count - 1 To 0 Step -1` – LarsTech Feb 29 '16 at 18:04
  • Possible duplicate of [Possible to iterate backwards through a foreach?](http://stackoverflow.com/questions/1211608/possible-to-iterate-backwards-through-a-foreach) – Icemanind Feb 29 '16 at 18:35

2 Answers2

2

Access the list by an index that starts at the count of elements in the collection and decrements by one.

For i as Integer = PixelList.Count - 1 To 0 Step -1
    If DirectCast(PixelList(i), Pixel).PixelNumber = 1 then DirectCast(PixelList(i), Pixel).NewColour()
Next
2

вʀaᴎᴅᴏƞ вєнᴎєƞ's way is the most efficient, but a simple alternative would be to use the List(Of T).Reverse() function, though that changes the order of the list itself.

    PixelList.Reverse()
    For Each Tile As Pixel In PixelList
        If Tile.PixelNumber = 1 Then
            Tile.NewColour()
        End If
    Next
j.i.h.
  • 815
  • 8
  • 29
  • 1
    Using the `Reverse()` method on the `List` would work, however going off of the question as stated, it would seem that there will be two loops working on the same list; one going top down, and the other going in reverse order. using the `Reverse()` method to reverse the list every time one of the loops needs it and then keeping track of which order the list is in at a given moment will add a significant amount of overhead and just adds unneeded complicatedness. – вʀaᴎᴅᴏƞ вєнᴎєƞ Feb 29 '16 at 18:28