Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Iterating through a Dictionary Object's Items in VB.NET and C#

0.00/5 (No votes)
27 Dec 2012 1  
Iterating through a Dictionary object may seem complicated in principle but in practice it is farily straightforward, and this involves looping

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Iterating through a Dictionary object may seem complicated in principle but in practice it is farily straightforward, and this involves looping through each of the KeyValuePair objects in each Dictionary item: -

VB.NET

Dim DictObj As New Dictionary(Of Integer, String)

DictObj.Add(1, "ABC")
DictObj.Add(2, "DEF")
DictObj.Add(3, "GHI")
DictObj.Add(4, "JKL")

For Each kvp As KeyValuePair(Of Integer, String) In DictObj
     Dim v1 As Integer = kvp.Key
     Dim v2 As String = kvp.Value
     Debug.WriteLine("Key: " + v1.ToString _
            + " Value: " + v2)
Next

C#

Dictionary<int, String> DictObj =
      new Dictionary<int, String>();

DictObj.Add(1, "ABC");
DictObj.Add(2, "DEF");
DictObj.Add(3, "GHI");
DictObj.Add(4, "JKL");

foreach (KeyValuePair<int,String> kvp in DictObj)
{
    int v1 = kvp.Key;
    String v2 = kvp.Value;
    Debug.WriteLine("Key: " + v1.ToString() +
         " Value: " + v2);
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here