Vadim's Weblog

Never stop learning.

foreach with Generic Dictionary

Posted by Vadim on March 30, 2008

I decided to write this post because few people approached me with the question:  “Is there a way to use foreach iteration statement with Dictionary<TKey, TValue> object?”

The quick response is: “Yes, use KeyValuePair.”

However, it wasn’t enough and I had to show an example.

Before I will show an example here, I want to remind you that Dictionary<TKey, TValue> class implements IDictionary<TKey, TValue> interface that extends ICollection<KeyValuePair<TKey, TValue> which in it turn is derived Dictionary Object from IEnumerable<KeyValuePair<TKey, TValue>.  As we know every class that implements IEnumerable interface must implement the GetEnumerator method.  And that is the reason why we can use foreach iteration statement.

Here’s the promised example.

   1: // Create a Dictionary object and load it with values.
   2: Dictionary<string, double> employeesWage = new Dictionary<string, double>();
   3: employeesWage.Add("Tom", 20000);
   4: employeesWage.Add("John", 15200);
   5: employeesWage.Add("Chris", 35000);
   6: employeesWage.Add("Brian", 38000);
   7:  
   8: // Enumerate and display
   9: foreach (KeyValuePair<string, double> pair in employeesWage)
  10:   Console.WriteLine("{0} makes {1:C}", pair.Key, pair.Value);

2 Responses to “foreach with Generic Dictionary”

  1. Stlan said

    It is also possible to just enumerate the keys or the values defined in your dictionary, by writing :
    foreach(string name in employees.Keys) {}
    foreach(double wage in employees.Values) {}

  2. vkreynin said

    Stlan, thanks for the valuable comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: