Tutorial :asp.net: how to access to each element of dictionary without using key?


i want to access each object of my dictionary Dictionary with int index. hw to do that.


Dictionary<KeyType, ValueType> myDictionary = . . .      foreach(KeyValuePair<KeyType, ValueType> item in myDictionary)  {     Console.WriteLine("Key={0}: Value={1}", item.Key, item.Value);  }  


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


Or if you work from Visual Studio 2008 you might:

foreach(var item in myDictionary)  {     . . .   }  


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »