Exploring Dictionary Iteration in C#: Step-by-Step Guide


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<stringint> dict = new Dictionary<stringint>();

dict.Add("apple", 3);

dict.Add("banana", 2);

dict.Add("cherry", 5);

foreach (KeyValuePair<stringint> 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<stringint> dict = new Dictionary<stringint>();

        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.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...