Use the foreach loop. : Foreach « Statement « C# / CSharp Tutorial






The foreach loop is used to cycle through the elements of a collection.

The general form of foreach is shown here:

foreach(type var-name in collection) 
       statement;
using System; 
 
class MainClass { 
  public static void Main() { 
    int sum = 0; 
    int[] nums = new int[10]; 
 
    for(int i = 0; i < 10; i++)  
      nums[i] = i; 
 
    Console.WriteLine("use foreach to display and sum the values");
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
    } 
    Console.WriteLine("Summation: " + sum); 
  } 
}
use foreach to display and sum the values
Value is: 0
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Summation: 45








4.4.Foreach
4.4.1.Use the foreach loop.
4.4.2.Use break with a foreach.
4.4.3.Use foreach on a two-dimensional array.
4.4.4.Search an array using foreach.