InterviewSolution
Saved Bookmarks
| 1. |
How to iterate over a dictionary in C# |
|
Answer» Different Key-Value pairs are REPRESENTED using the dictionary collection. This is somewhat similar to an English dictionary which has different words along with their meanings. The dictionary collection is included in the System.Collections.Generic NAMESPACE. The FOREACH loop can be used to iterate over the dictionary in C#. A program that demonstrates this is given as follows: using System; using System.Collections.Generic; namespace Demo { class Example { STATIC void Main(string[] args) { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1,"James"); dict.Add(2,"Amy"); dict.Add(3,"Adam"); dict.Add(4,"Peter"); dict.Add(5,"Susan"); Console.WriteLine("The dictionary elements are given as follows:"); foreach (KeyValuePair<int, string> i in dict) { Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value); } } } }The output of the above program is as follows: The dictionary elements are given as follows: Key: 1 Value: James Key: 2 Value: Amy Key: 3 Value: Adam Key: 4 Value: Peter Key: 5 Value: Susan |
|