Is it possible to have a foreach
statement that will traverse through a Collections object in reverse order?
If not a foreach
statement, is there another way?
To print an array in reverse order, we shall know the length of the array in advance. Then we can start an iteration from length value of array to zero and in each iteration we can print value of array index. This array index should be derived directly from iteration itself.
To traverse in reverse order, we can use the reverse_iterator. Here we will use the rbegin() and rend() function to get the begin and end of the reverse iterator.
So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.
To use the forEach() method on an array in reverse order: Use the slice() method to get a copy of the array. Use the reverse() method to reverse the copied array.
You can use a normal for
loop backwards, like this:
for (int i = collection.Count - 1; i >= 0 ; i--) {
var current = collection[i];
//Do things
}
You can also use LINQ:
foreach(var current in collection.Reverse()) {
//Do things
}
However, the normal for
loop will probably be a little bit faster.
If you're using 3.5, looks like there is a Reverse() method in LINQ That won't iterate through in reverse order, but would reverse the entire list, then you could do your foreach.
Or you could use a simple for statement:
for(int i = list.Count -1; i >= 0; --i)
{
x = list[i];
}
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