65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (1 vote)

Oct 11, 2013

CPOL
viewsIcon

40246

Iterating through a Dictionary object may seem complicated in principle but in practice it is farily straightforward, and this involves looping

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);
}