I don't believe this is possible by conventional methods, but something like this verbose code:
For Each s As String In myStringList Step -1
//' Do stuff here
Next
I will probably have to invert the myString object before a conventional For..Each Loop, correct?
Best Answer
I think the documentation referenced in Mike's answer below is extremely misleading. The order of
For Each
is defined by the collection it's called (i.e. its implementation ofIEnumerable
/IEnumerable<T>
), but that's not the same as saying it shouldn't be used when the order is important. Many collections (such as arrays,List<T>
etc) always go in the "natural" order.Part of the documentation does allude to this:
That's not at all the same as saying it can't be relied upon - it can be relied upon if you know that the collection you're iterating over will produce the results in the desired order. It's not like it's going to pick elements at random. The behaviour in terms of
IEnumerable
/IEnumerable<T>
is clearly defined on that page.The most important exceptions to predictable orderings are dictionaries and sets, which are naturally unordered.
To reverse an
IEnumerable<T>
, useEnumerable.Reverse
- but if you need to iterate in reverse over a collection which is indexed by position (such as an array orList<T>
) then it would be more efficient to use aFor
loop starting at the end and working backwards.