Showing posts with label For Each. Show all posts
Showing posts with label For Each. Show all posts

Sunday, December 2, 2007

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

Iterating through a Dictionary Object's items may be more complicated than you think; however, with a few examples to go by it turns out to be pretty easy:

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


It should also be pointed out that you can obtain a collection from the Dictionary Object for both Keys and Values using KeyCollection and ValueCollection:

VB.NET

Dim keyCollection As _
Dictionary(Of Integer, String).KeyCollection = _
DictObj.Keys

For Each key As Integer In keyCollection
Debug.WriteLine("Key: " + key.ToString())
Next

Dim valueCollection As _
Dictionary(Of Integer, String).ValueCollection = _
DictObj.Values

For Each value As String In valueCollection
Debug.WriteLine("Value: " + value.ToString())
Next


C#

Dictionary<int,String>.KeyCollection keyCollection=
DictObj.Keys;

foreach (int key in keyCollection)
{
Debug.WriteLine("Key: " + key.ToString());
}

Dictionary<int,String>.ValueCollection valueCollection = DictObj.Values;

foreach (String value in valueCollection)
{
Debug.WriteLine("Value: " + value.ToString());
}


For more examples see:

http://msdn2.microsoft.com/en-us/library/xfhwa508.aspx