i want to access each object of my dictionary Dictionary with int index. hw to do that.
+2
A:
Dictionary<KeyType, ValueType> myDictionary = . . .
foreach(KeyValuePair<KeyType, ValueType> item in myDictionary)
{
Console.WriteLine("Key={0}: Value={1}", item.Key, item.Value);
}
Binary Worrier
2009-05-13 10:20:39
. . . assuming it's a generic dictionary, sorry
Binary Worrier
2009-05-13 10:22:01
+1 Simple and clear!
Issa Qandil
2009-05-13 10:22:49
A:
You can use a foreach loop as shown below:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("key1", "value2");
dict.Add("key2", "value");
foreach (KeyValuePair<string, string> item in dict)
Console.WriteLine(item.Key + "=" + item.Value);
mdresser
2009-05-13 10:22:57
+1
A:
Or if you work from Visual Studio 2008 you might:
foreach(var item in myDictionary)
{
. . .
}
Valentin Vasiliev
2009-05-13 10:29:43
Noting type of item with be KeyValuePair<TKey, TValue> (where myDictionary is IDictionary<TKey, TValue>).
Richard
2009-05-13 10:50:41
A:
My favourite approach is this one (even though I guess any solution given so far will do the trick for you):
// set up the dictionary
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("A key", "Some value");
dictionary.Add("Another key", "Some other value");
// loop over it
Dictionary<string, string>.Enumerator enumerator = dictionary.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current.Key + "=" + enumerator.Current.Value);
}
Fredrik Mörk
2009-05-13 10:51:32