Possible to iterate backwards through a foreach?

I know I could use a for statement and achieve the same effect, but can I loop backwards through a foreach loop in C#?


If you are on .NET 3.5 you can do this:

IEnumerable<int> enumerableThing = ...;
foreach (var x in enumerableThing.Reverse())

It isn't very efficient as it has to basically go through the enumerator forwards putting everything on a stack then pops everything back out in reverse order.

If you have a directly-indexable collection (e.g. IList) you should definitely use a for loop instead.

If you are on .NET 2.0 and cannot use a for loop (i.e. you just have an IEnumerable) then you will just have to write your own Reverse function. This should work:

static IEnumerable<T> Reverse<T>(IEnumerable<T> input)
{
    return new Stack<T>(input);
}

This relies on some behaviour which is perhaps not that obvious. When you pass in an IEnumerable to the stack constructor it will iterate through it and push the items onto the stack. When you then iterate through the stack it pops things back out in reverse order.

This and the .NET 3.5 Reverse() extension method will obviously blow up if you feed it an IEnumerable which never stops returning items.


When working with a list (direct indexing), you cannot do it as efficiently as using a for loop.

Edit: Which generally means, when you are able to use a for loop, it's likely the correct method for this task. Plus, for as much as foreach is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach for looping.