What is the method for traversing a dictionary in C#?

In C#, the foreach loop can be used to iterate over a dictionary. Here is an example:

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);

foreach (KeyValuePair<string, int> kvp in dict)
{
    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}

The code above creates a dictionary with string keys and integer values. It then uses a foreach loop to iterate through each key-value pair in the dictionary, printing out the key and its corresponding value.

 

More tutorials

How to add elements to a C# dictionary(Opens in a new browser tab)

How to retrieve a value from a C# dictionary using a key?(Opens in a new browser tab)

jQuery parent() and children() tree traversal functions(Opens in a new browser tab)

How can I include new entries in a Python dictionary?(Opens in a new browser tab)

a certain value exists in a dictionary in C#(Opens in a new browser tab)

BroadcastReceiver Example Tutorial on Android(Opens in a new browser tab)

Tutorial on how to set up a Hibernate Tomcat JNDI DataSource.(Opens in a new browser tab)

QR code generator in Java using zxing.(Opens in a new browser tab)

Java thread ensuring Java code is thread-safe(Opens in a new browser tab)

Spring MVC HandlerInterceptorAdapter and HandlerInterceptor.(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds