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", "555-0150");
phones.Add("Enju", "555-0199");
phones.Add("Molly", "555-0151");
phones.Add("James", "555-0142");
phones.Add("Ahmed", "555-0128");
phones.Add("Leah", "555-0100");

// Iterate through the collection.
System.Console.WriteLine("Name\t\tNumber");
foreach (string name in phones.Keys) 
{
    System.Console.WriteLine(name +"\t"+ phones[name]);
}

Compiling the Code

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

  • Add a using directive to the System.Collections namespace.

See Also

Concepts

C# Language Primer

Arrays and Collections

Other Resources

Visual C# Express