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!
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
If you don't mind the overhead it creates, you could use reverse :
list.reverse()
for each listElement in list
' ...
next
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With