C# foreach Reference Tutorial

The foreach statement in C# iterates through a collection of items. This article contains several foreach loop code examples in C#.

The foreach statement in C# iterates through a collection of items such as an array or list, The foreach body must be enclosed in {} braces unless it consists of a single statement.
 
The code in Listing 1 creates an array of odd numbers and uses foreach loop to loop through the array items and read them.
  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {  
  7.         Console.WriteLine("foreach loop Sample!");  
  8.         int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };  
  9.         foreach (int num in oddArray)  
  10.         {  
  11.             Console.WriteLine(num);  
  12.         }  
  13.         Console.ReadKey();  
  14.     }  
  15. }  
Listing 1.
 
The output of Listing 1 looks like Figure 1.
 
 
 
Figure 1.  

If you’re not familiar with Arrays in C#, please read article: Arrays Tutorial in C#. 

Listing 2 is an example of for loop that can also be used read an array items.
  1. for (int counter = 0; counter < oddArray.Length; counter++)  
  2. {  
  3.     Console.WriteLine(oddArray[counter]);  
  4. }  
Listing 2.
 
You can stop and exit a foreach loop by using the break, return, goto, and throw statements. The code snippet in Listing 3 quits execution once the number equals to 15. 
  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {  
  7.         Console.WriteLine("foreach loop Sample!");  
  8.         // Array of odd numbers  
  9.         int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };  
  10.         // Loop through array items  
  11.         foreach (int num in oddArray)  
  12.         {  
  13.             Console.WriteLine(num);  
  14.             // Don't read any number after 15  
  15.             if (num == 15) break;  
  16.         }  
  17.         Console.ReadKey();  
  18.     }  
  19. }  
Listing 3.
 

Use foreach to find a char in a string

Remember your early days, when you need to find a character in a string. We can use foreach loop for this to check one character at a time in a string using a foreach,in loop. Strings are an important . Strings in C#

Code snippet in Listing 4 creates an array of chars from a string and reads one character at a time. The code also makes sure that whitespace between characters is skipped.

  1. // Read a string - one character at a time and if space, skip it  
  2. string name = "Mahesh Chand Beniwal";  
  3.   
  4. // Convert string into an array of chars  
  5. char[] chArray = name.ToCharArray();  
  6.   
  7. // Loop through chars and display one char at a time  
  8. foreach (char ch in chArray)  
  9. {  
  10. if (ch.ToString() != " ")  
  11. Console.WriteLine(ch);  
  12. }  

Listing 4. 

Foreach in Collection

Let’s look at another use of the foreach, in loop. Do you remember your early programming days when you need to go through a string and find the number of occurrences of a character in a string? The code in Listing 5 does the same using a foreach, in loop.

  1. // Find number of occurrences of a char in a string  
  2. string str = "A monkey stole a banana, climb on a tree and ate it.";  
  3. char[] chars = str.ToCharArray();  
  4. int ncount = 0;  
  5. // Loop through chars and find all 'n' and count them  
  6. foreach (char ch in chars)  
  7. {  
  8. if (ch == 'n')  
  9. ncount++;  
  10. }  
  11. Console.WriteLine($"Total n found {ncount}");  

Listing 5. 

Foreach in Array

Here is another example of using a foreach, in loop. The code snippet in Listing 6 creates an array of strings, reads and display each string one at a time.

  1. // Array of authors - string  
  2. string[] authorList = new string[]  
  3. "Mahesh Chand""Raj Kumar""Naveen Sharma""Allen O'neill""Dave McCarter" };  
  4. // Loop through array and read all authors  
  5. foreach (string author in authorList )  
  6. {  
  7. Console.WriteLine(author);  
  8. }  

Listing 6. 

Summary

The foreach, in loop in C# is used to loop through the items in a collection. In this article and code samples, we saw various usage of the foreach, in loop. 

Next reading: The for vs foreach in C#