views:

763

answers:

4

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
. . . assuming it's a generic dictionary, sorry
Binary Worrier
+1 Simple and clear!
Issa Qandil
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
Oops, a bit late there...
mdresser
+1  A: 

Or if you work from Visual Studio 2008 you might:

foreach(var item in myDictionary)
{
   . . . 
}
Valentin Vasiliev
Noting type of item with be KeyValuePair<TKey, TValue> (where myDictionary is IDictionary<TKey, TValue>).
Richard
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