I know I could use a for
statement and achieve the same effect, but can I loop backwards through a foreach
loop in C#?
As 280Z28 says, for an IList
you can just use the index. You could hide this in an extension method:
public static IEnumerable FastReverse(this IList items)
{
for (int i = items.Count-1; i >= 0; i--)
{
yield return items[i];
}
}
This will be faster than Enumerable.Reverse()
which buffers all the data first. (I don't believe Reverse
has any optimisations applied in the way that Count()
does.) Note that this buffering means that the data is read completely when you first start iterating, whereas FastReverse
will "see" any changes made to the list while you iterate. (It will also break if you remove multiple items between iterations.)
For general sequences, there's no way of iterating in reverse - the sequence could be infinite, for example:
public static IEnumerable GetStringsOfIncreasingSize()
{
string ret = "";
while (true)
{
yield return ret;
ret = ret + "x";
}
}
What would you expect to happen if you tried to iterate over that in reverse?