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

9 comments:

Anonymous said...

Great, thanks!

Anonymous said...

but chyo, can you delete items from the dictionary within the iteration?

you can't delete something inside a foreach loop because it throws an exception like "collection was modified"

Anonymous said...

thank you man, great work. it helped me alot.
sheraz

Randall said...

great tip. Just what I was looking for, Thanks so much.

papararapap said...

wow great! thanks bro.

Anonymous said...

"but chyo, can you delete items from the dictionary within the iteration?"
Make a "todelete" list with keys of items that you want to delete and after finishing iterating through dictionary, iterate through "todelete" list and delete.

Anonymous said...

This is excellent. It makes the whole process so easy to understand and follow.

Anonymous said...

great help, thanks!

lingmaaki said...

For Each pair As KeyValuePair(Of String, String) In dict

MsgBox(pair.Key & " - " & pair.Value)

Next


http://vb.net-informations.com/collections/dictionary.htm

Ling