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
Great, thanks!
ReplyDeletebut chyo, can you delete items from the dictionary within the iteration?
ReplyDeleteyou can't delete something inside a foreach loop because it throws an exception like "collection was modified"
thank you man, great work. it helped me alot.
ReplyDeletesheraz
great tip. Just what I was looking for, Thanks so much.
ReplyDeletewow great! thanks bro.
ReplyDelete"but chyo, can you delete items from the dictionary within the iteration?"
ReplyDeleteMake a "todelete" list with keys of items that you want to delete and after finishing iterating through dictionary, iterate through "todelete" list and delete.
This is excellent. It makes the whole process so easy to understand and follow.
ReplyDeletegreat help, thanks!
ReplyDeleteFor Each pair As KeyValuePair(Of String, String) In dict
ReplyDeleteMsgBox(pair.Key & " - " & pair.Value)
Next
http://vb.net-informations.com/collections/dictionary.htm
Ling