Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use "For Each" statement from the last element in a list to the first

When I want to iterate from the last element in a list to the first one, I usually do like this:

For i=list.Count-1 to 0 Step -1
    'do something
Next

I was wondering if there is a way to use the For Each statement iterating through the list this way.

Thanks!

like image 486
Tao Gómez Gil Avatar asked Dec 06 '22 05:12

Tao Gómez Gil


2 Answers

This can be done with Enumerable.Reverse. If list is typed as IEnumerable, you can call it like this:

For Each item in list.Reverse()
Next

However if it is ArrayList or List(Of T), this will call the Reverse method which modifies the list (and doesn't return anything). In that case you could call from Enumerable directly or use AsEnumerable:

For Each item in Enumerable.Reverse(list)
Next

For Each item in list.AsEnumerable().Reverse()
Next

Something to be aware of is that this method will copy the list to an array. If you need to save memory, it would be better to use the For...To method. You could wrap this into your own iterator function extension method though:

<Extension()>
Public Iterator Function LazyReverse(Of T)(source As IList(Of T)) As IEnumerable(Of T)
    For i = source.Count - 1 To 0 Step -1
        Yield source.Item(i)
    Next
End Function

Then call it any time like:

For Each item in list.LazyReverse()
Next
like image 159
nmclean Avatar answered May 12 '23 20:05

nmclean


If you don't mind the overhead it creates, you could use reverse :

list.reverse()
for each listElement in list
' ...
next
like image 23
GameAlchemist Avatar answered May 12 '23 20:05

GameAlchemist