Enumerating a Dictionary<> Object

In C# using .Net 2.0+, there is now built-in support for Generics collections using the System.Collections.Generic namespace. I use the List type most often, as a strongly-typed substitute for the ArrayList. Since it is strongly-typed, you now have design-time type-checking for enumerations like this (no casting necessary):

List<int> Foos = new List<int>();
foo.Add(new foo(1));
foo.Add(new foo(2));
foreach (foo f in Foos) {

The second-most useful Generic (in my opinion) is Dictionary. This is a strongly-typed hashtable, where you can determine the types of both X (the Key) and Y (the Value). Like other Generic collections, the Dictionary object type is also Enumerable (meaning that you can use statements like foreach to automatically parse its contents in order). However, since there are two different types of value stored in a Generic Dictionary object, how do you call an strongly-typed enumeration statement like foreach? This is done by referencing each pair of values as a KeyValuePair object (which is another type of Generic supported by System.Collections.Generic”) and can be performed as follows (ref)

Dictionary<string, int> PhoneNumbers = new Dictionary<string, int>();
PhoneNumbers.Add("Jones, Jim", "800-555-2312");
PhoneNumbers.Add("Smith, Beth", "324-555-6742");
foreach(KeyValuePair<string, int> personNumber in PhoneNumbers) {
  Console.PrintLine(personNumber.Key + "\t" + personNumber.Value);
Tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *