Dictionary access
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 31 32 33 34 35 36 37 38 39 40 |
class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Great Frigatebird"}, {2,"Hammerkop"}, {3,"Great White Pelican"}, {4,"Australian Pelican"}, {5,"American White Pelican"} }; Console.WriteLine("dictionary elements using foreach loop..."); //get dictionary elements using foreach loop. foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.WriteLine("\ndictionary elements using for loop..."); //get dictionary items by index for (int i = 0; i < birds.Count; i++) { Console.WriteLine(birds.ElementAt(i).Key+ "......." + birds.ElementAt(i).Value); } Console.WriteLine("\nother way to access dictionary elements..."); Console.WriteLine(birds[3]); //get dictionary first element. Console.WriteLine(birds.First().Key + "........" + birds.First().Value); //get dictionary last element. Console.WriteLine(birds.Last().Key + "........" + birds.Last().Value); Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
dictionary elements using foreach loop... 1 ........ Great Frigatebird 2 ........ Hammerkop 3 ........ Great White Pelican 4 ........ Australian Pelican 5 ........ American White Pelican dictionary elements using for loop... 1.......Great Frigatebird 2.......Hammerkop 3.......Great White Pelican 4.......Australian Pelican 5.......American White Pelican other way to access dictionary elements... Great White Pelican 1........Great Frigatebird 5........American White Pelican |