C# Source Code: Looping over the keys/values in a StringDictionary
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Looping over the keys/values in a StringDictionary
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, July 21, 2004
Hits:
1051
Category:
General/Framework
Article:
Below is a demonstration console application which shows two different methods of looping over the keys and values contained in a StringDictionary. using System; using System.Collections; using System.Collections.Specialized; public class VBusersCollections { public static void Main() { //Creates and initialise a StringDictionary. StringDictionary myCol = new StringDictionary(); myCol.Add("employee1", "Andrew Baker"); myCol.Add("employee2", "Shannon Baker"); myCol.Add("employee3", "Another Baker"); //Display the values in the StringDictionary //Method 1 DictionaryDisplayKeyValues1( myCol ); //Method 2 DictionaryDisplayKeyValues2( myCol ); Console.ReadLine(); } ///
/// Demonstrates how to loop over the items in a collection using a foreach loop ///
public static void DictionaryDisplayKeyValues1(StringDictionary dict ) { //Display the dictionaries contents using a for each loop Console.WriteLine(); Console.WriteLine("Displays the elements using a foreach loop:"); foreach (DictionaryEntry de in dict ) { //The {0,-20} pads the key to 20 chars long Console.WriteLine( "{0,-20} {1}", de.Key, de.Value ); } } ///
/// Demonstrates how to loop over the items in a collection using a for loop, /// the indexer and copying the keys to an array ///
public static void DictionaryDisplayKeyValues2( StringDictionary myCol ) { //Size a string array to hold the keys String[] myKeys = new String[myCol.Count]; //Copy the keys into the array myCol.Keys.CopyTo(myKeys, 0 ); //Display the dictionaries contents using a for loop Console.WriteLine(); Console.WriteLine("Displays the elements using a for loop:"); for ( int i = 0; i < myCol.Count; i++ ) { //The {0,-16} pads the key to 16 chars long Console.WriteLine( "[{0}] {1,-16} {2}", i, myKeys[i], myCol[myKeys[i]] ); } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet