This documentation is archived and is not being maintained.

Code: Iterating Through a Collection (Visual C#)

Visual Studio .NET 2003

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.


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("Nelly", "110-5699");
phones.Add("Leah", "922-5699");

// Iterate through the collection.
foreach (string name in phones.Keys) 
    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

Iteration Statements | foreach, in | System.Collections Namespace | Hashtable Class | Using foreach with Collections| General Language Example Topics