C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
We can 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 has no obvious way to go backwards.
Example. First, you can't use a foreach-loop in the reverse direction over every collection, as some collections are generated as you go along. However, many collections, IEnumerable ones, can.
Tip: There is a Reverse<T>() method that "inverts" the order of elements in an IEnumerable collection.
C# program that uses Reverse 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 i
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.
Note: In part 1 above, we specify <string> before the parameter list for Reverse. We want the Reverse method that acts on strings.
Also, 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.
Tip: For this reason, only use it when correctness is far more important than speed.
Summary. We saw that foreach is a powerful keyword for reducing bugs in loops, but it has no easy way to enumerate backwards. By using the Reverse extension method from System.Linq, we can do just that.
Caution: Reverse is creating a new IEnumerable collection, not simply doing a reverse iteration, making it less efficient.