The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects. The statement takes the following form:
foreach (type identifier in expression) statement
where:
The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.
In this section, the following topics are discussed in detail:
When used with an array, the foreach statement repeats the embedded statement(s) for each element in the array.
In this example, an array of integers is searched for even and odd numbers. A counter for each type of number stores the number of occurrences.
// Using foreach with arrays using System; class MainClass { public static void Main() { int odd = 0, even = 0; int[] arr = new int [] {0,1,2,5,7,8,11}; foreach (int i in arr) { if (i%2 == 0) even++; else odd++; } Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.", odd, even) ; } }
Found 4 Odd Numbers, and 3 Even Numbers.
To iterate through a collection, the collection must meet specific requirements. For example, in the following foreach statement:
foreach (ItemType item in myCollection)
myCollection
must meet the following requirements:
Enumerator
(explained below).Enumerator
(a class or struct) must contain:
ItemType
or a type that can be converted to it. The property accessor returns the current element of the collection.There are three approaches to using collections:
The following examples demonstrate the three approaches.
Example | Demonstrates | Comment |
---|---|---|
Example 1 | A C#-specific collection. | This example creates a collection by using the instructions above. |
Example 2 | A generic collection. | This example creates a collection by using the instructions above and implements the IEnumerable and IEnumerator interfaces. |
Example 3 | Using one of the predefined collection classes. | This example creates a Hashtable instance and uses the Hashtable class members to manipulate the collection. The Hashtable class represents a dictionary of associated keys and values, implemented as a hash table. |
For more information on the interfaces IEnumerator and IEnumerable, and the Hashtable class, see the System.Collections section in the NGWS SDK.
// Using foreach with C#-specific collections: using System; // Declare the collection: public class MyCollection { int[] items; public MyCollection() { items = new int[5] {12, 44, 33, 2, 50}; } public MyEnumerator GetEnumerator() { return new MyEnumerator(this); } // Declare the enumerator class: public class MyEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < collection.items.GetLength(0)); } public int Current { get { return(collection.items[nIndex]); } } } } public class MainClass { public static void Main() { MyCollection col = new MyCollection(); Console.WriteLine("Values in the collection are:"); // Display collection items: foreach (int i in col) { Console.WriteLine(i); } } }
Values in the collection are: 12 44 33 2 50
This example repeats the same algorithm of Example 1, but uses a generic collection that can be enumerated from other languages such as Visual Basic. This type of collection must implement the IEnumerable interface from the System.Collections namespace.
// Using foreach with a generic collection using System; using System.Collections; // Declare the collection and implement the IEnumerable interface: public class MyCollection: IEnumerable { int[] items; public MyCollection() { items = new int[5] {12, 44, 33, 2, 50}; } public MyEnumerator GetEnumerator() { return new MyEnumerator(this); } // Implement the GetEnumerator() method: IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // Declare the enumerator and implement the IEnumerator interface: public class MyEnumerator: IEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < collection.items.GetLength(0)); } public int Current { get { return(collection.items[nIndex]); } } // The current property on the IEnumerator interface: object IEnumerator.Current { get { return(Current); } } } } public class MainClass { public static void Main(string [] args) { MyCollection col = new MyCollection(); Console.WriteLine("Values in the collection are:"); // Display collection items: foreach (int i in col) { Console.WriteLine(i); } } }
Values in the collection are: 12 44 33 2 50
In this example, the predefined Hashtable collection class is used. By using the System.Collections namespace in your program, you can have access to the Hashtable class and its members. To add entries to the Hashtable object, use the Add method.
// Using the Hashtable collection class using System; using System.Collections; public class MainClass { public static void Main(string [] args) { // Declare a Hashtable object: Hashtable ziphash = new Hashtable(); // Add entries using the Add() method: ziphash.Add("98008", "Bellevue"); ziphash.Add("98052", "Redmond"); ziphash.Add("98201", "Everett"); ziphash.Add("98101", "Seattle"); ziphash.Add("98371", "Puyallup"); // Display contents: Console.WriteLine("Zip code\tCity"); foreach (string zip in ziphash.Keys) { Console.WriteLine(zip + "\t\t" + ziphash[zip]); } } }
Zip code City 98201 Everett 98052 Redmond 98101 Seattle 98008 Bellevue 98371 Puyallup