How can you reverse a foreach-loop? You want to use a foreach-loop over a collection in the reverse order. The keyword foreach is useful making loops simpler and less prone to bugs, but it doesn't have an obvious way to go backwards.

This C# program shows the foreach loop used with a Reverse extension method call.
First, you can't use foreach in the reverse direction over every collection, as some collections are generated as you go along. However, many collections, IEnumerable ones, can. There is a Reverse<T>() method that "inverts" the order of elements in an IEnumerable collection.
Program that uses Reverse [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Example string array
string[] arr = new string[]
{
"cat",
"apple",
"macintosh",
"i"
};
// 1
// Use the Reverse generic extension method.
// Note how <string> is specified before the params.
foreach (string s in arr.Reverse<string>())
{
Console.WriteLine(s);
}
// 2
// Use the Reverse generic extension method,
// but omit the <string> part. This is sometimes OK.
foreach (string s in arr.Reverse())
{
Console.WriteLine(s);
}
}
}
Output
Output is repeated twice.
i
macintosh
apple
cat
iDescription. Reverse is an extension method, meaning it is really a static method that uses special syntax like an instance method. It receives an IEnumerable collection, which includes arrays (string[]) and Lists. In part 1 above, we specify <string> before the parameter list for Reverse. This tells the C# compiler that you want the Reverse method that acts on strings.
Extension Method
More information. As an aside, for some collections that implement their own Reverse method, you need to specify the <string> to indicate you want the extension method, not the regular one. This method is slower than using reverse iteration on a for-loop. For this reason, only use it when correctness is far more important than speed.
For Loops
We saw that foreach is a powerful keyword for reducing bugs in loops, but it doesn't have an easy way to enumerate backwards. By using the Reverse extension method, we can do just that. Under the hood, Reverse is actually creating a new IEnumerable collection, not simply doing a reverse iteration, making it less efficient. You can find more information on this foreach-loop on this site.
Foreach Loop Examples Loop Constructs