To iterate through a dictionary in C#, you can use a `foreach` loop or a `for` loop.
Here's an example of using a `foreach` loop to iterate through a dictionary:
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("apple", 3); dict.Add("banana", 2); dict.Add("cherry", 5); foreach (KeyValuePair<string, int> pair in dict) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); } |
In this example, we have a dictionary that maps strings
to integers. We use a `foreach` loop to iterate over the key-value pairs in the
dictionary and print each key-value pair to the console.
Alternatively, you can use a `for` loop to iterate through the keys or values of the dictionary:
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("apple", 3); dict.Add("banana", 2); dict.Add("cherry", 5);
for (int i = 0; i<dict.Count; i++) { string key = dict.Keys.ElementAt(i); int value = dict.Values.ElementAt(i); Console.WriteLine("{0}: {1}", key, value); } |
In this example, we use a `for` loop to iterate over
the keys and values in the dictionary and print each key-value pair to the
console. We use the `Keys` and `Values` properties of the dictionary to get the
keys and values as `IEnumerable` collections, and then use the `ElementAt`
method to get the key and value at each index.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.