Foreach key in dictionary
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {11,"Eurasian Curlew"}, {22,"Whimbrel"}, {33,"Common Redshank"}, {44,"Wandering Tattler"}, {55,"Greater Yellowlegs"} }; Console.WriteLine("dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.WriteLine("\ndictionary keys only.........."); //get only keys of dictionary. foreach (int key in birds.Keys) { Console.WriteLine(key); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | dictionary keys and values.......... 11 ........ Eurasian Curlew 22 ........ Whimbrel 33 ........ Common Redshank 44 ........ Wandering Tattler 55 ........ Greater Yellowlegs dictionary keys only.......... 11 22 33 44 55 |