Continuing from a previous post on Using C# Dictionary Collection, the next most common tasks is enumerate through every element in the Dictionary. To begin, each element in a Dictionary is a KeyValuePair. According to the C# documentation for Dictionary, the order of a KeyValuePair enumeration is not defined. Therefore, the KeyValuePair order may not be the same as the insertion (or Add) order. For that reason, we cannot use a for loop. Instead, a foreach loop is our solution. In this tutorial, I will demonstrate how to loop through the KeyValuePair, the Key, and the Value of a dictionary.
Foreach KeyValuePair
In this first example, we will be looping through the KeyValuePair. We can get both the key (as an int) and the value (as a string) from the KeyValuePair. Note that the type of the KeyValuePair must be declared in the foreach loop.
Dictionary myDictionary = new Dictionary();
myDictionary.Add(1, "ABC");
myDictionary.Add(2, "DEF");
foreach (KeyValuePair pair in myDictionary)
{
int key = pair.Key;
string value = pair.Value;
Debug.WriteLine("Key: " + key.ToString() + " Value: " + value);
}
Foreach Key
In this second case, we will be looping through all Keys in the Dictionary. The Keys must be unique and in this example, the key is an integer.
Dictionary myDictionary = new Dictionary();
myDictionary.Add(1, "ABC");
myDictionary.Add(2, "DEF");
foreach (int key in myDictionary.Keys)
{
Debug.WriteLine("Key: " + key.ToString());
}
Foreach Value
In this final case, we are looping through the Value of our dictionary. The value can be anything you define, but in our example, it is a string.
Dictionary myDictionary = new Dictionary();
myDictionary.Add(1, "ABC");
myDictionary.Add(2, "DEF");
foreach (string value in myDictionary.Values)
{
Debug.WriteLine("Value: " + value);
}
RSS Feed
Posted in
Tags: 

