Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you reverse traverse through a C# collection?

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?

like image 954
Sam F Avatar asked Jun 16 '10 18:06

Sam F


People also ask

How do you reverse a traverse array in C?

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.

How do you reverse a traverse?

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.

How do you reverse a traverse vector?

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.

How do you do a forEach backwards?

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.


2 Answers

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.

like image 146
SLaks Avatar answered Sep 19 '22 06:09

SLaks


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];
}
like image 30
taylonr Avatar answered Sep 23 '22 06:09

taylonr