In C#, there are several ways to iterate over a dictionary. Here are a few examples:
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);
}
In this example, we define a Dictionary<string, int>
and add some key-value pairs to it. We then use a foreach
loop to iterate over the dictionary and print out each key-value pair.
KeyValuePair
structDictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);
for (int i = 0; i < dict.Count; i++)
{
KeyValuePair<string, int> kvp = dict.ElementAt(i);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
In this example, we define a Dictionary<string, int>
and add some key-value pairs to it. We then use a for
loop to iterate over the dictionary by index. Inside the loop, we use the ElementAt
method to get the key-value pair at the current index and print out its key and value.
Keys
or Values
propertyDictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);
foreach (string key in dict.Keys)
{
Console.WriteLine("Key = {0}, Value = {1}", key, dict[key]);
}
foreach (int value in dict.Values)
{
Console.WriteLine("Value = {0}", value);
}
In this example, we define a Dictionary<string, int>
and add some key-value pairs to it. We then use two foreach
loops to iterate over the dictionary. The first loop uses the Keys
property to iterate over the keys, and the second loop uses the Values
property to iterate over the values. Inside each loop, we print out the current key or value.
All of these methods will produce the same output:
Key = apple, Value = 1
Key = banana, Value = 2
Key = cherry, Value = 3
Value = 1
Value = 2
Value = 3
The method you choose will depend on your specific use case and personal preference. In general, the foreach
loop is the simplest and most commonly used method for iterating over a dictionary in C#.