TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Foreach Reverse Loop

This C# program shows the foreach loop used with a Reverse extension method call.

Foreach reverse loop. How can you reverse a foreach-loop?

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.

Reverse

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.

Extension MethodStatic Method

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.

For

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf