How can you reverse traverse through a C# collection?

Sam F picture Sam F · Jun 16, 2010 · Viewed 21k times · Source

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?

Answer

SLaks picture SLaks · Jun 16, 2010

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.