In C#, you can iterate over a dictionary using a 'foreach' loop or a 'for' loop. Here are examples of both approaches:
Using a 'foreach' loop:
DictionaryOutput:myDict = new Dictionary () { {"apple", 1}, {"banana", 2}, {"cherry", 3} }; foreach (KeyValuePair kvp in myDict) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); }
Key = apple, Value = 1 Key = banana, Value = 2 Key = cherry, Value = 3Using a 'for' loop:
DictionaryOutput:myDict = new Dictionary () { {"apple", 1}, {"banana", 2}, {"cherry", 3} }; for (int i = 0; i < myDict.Count; i++) { Console.WriteLine("Key = {0}, Value = {1}", myDict.ElementAt(i).Key, myDict.ElementAt(i).Value); }
Key = apple, Value = 1 Key = banana, Value = 2 Key = cherry, Value = 3
Note that when using a 'foreach' loop, the loop variable 'kvp' is of type 'KeyValuePair', where 'TKey' and 'TValue' are the types of the dictionary's keys and values, respectively. When using a 'for' loop, you can access the dictionary's elements using the 'ElementAt' method, which returns an element at a specified index.
No comments:
Post a Comment