logo search
Учебник_ПОА

How to: Iterate Through an Array

This example uses the foreach statement to access and display items of an array.

Example

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

foreach (int element in numbers)

{

System.Console.WriteLine(element);

}

Compiling the Code

Copy the code and paste it into the Main method of a console application.

How to: Iterate Through a Collection

This example uses the Add method on the Hashtable class to add entries to a Hashtable collection. It then uses a foreach statement to iterate through the collection.

Example

Hashtable phones = new Hashtable();

// Add items.

phones.Add("John", "123-4567");

phones.Add("Enju", "351-8765");

phones.Add("Molly", "221-5678");

phones.Add("James", "010-4077");

phones.Add("Ahmed", "110-5699");

phones.Add("Leah", "922-5699");

// Iterate through the collection.

System.Console.WriteLine("Name\tNumber");

foreach (string name in phones.Keys)

{

System.Console.WriteLine(name +"\t"+ phones[name]);

}