BLOG.CSHARPHELPER.COM: Access the keys and values stored in a Dictionary in C#
Access the keys and values stored in a Dictionary in C#
The Dictionary object provides a KeyCollection named Keys and a ValueCollection named Values to let you access the keys and values stored in the Dictionary. These collections are slightly different from the List objects that you probably use in your code. In particular, you cannot use index these collections the way you can an array or List.
However, you can use a foreach loop to iterate through the collections and you can use ToArray to copy a collection's values into a normal array.
This example uses the following code to initialize a Dictionary.
The form's Load event handler then uses the following code to display the Dictionary's keys, values, and key/value pairs.
private void Form1_Load(object sender, EventArgs e)
{
// Display the keys.
foreach (int number in Numbers.Keys)
lstKeys.Items.Add(number);
// Convert the Dictionary's ValueCollection
// into an array and display the values.
string[] values = Numbers.Values.ToArray();
for (int i = 0; i < values.Length; i++)
lstValues.Items.Add(values[i]);
// Display the keys and values.
foreach (int number in Numbers.Keys)
lstKeysAndValues.Items.Add(number.ToString() +
": " + Numbers[number]);
}
First the code uses a foreach loop to iterate through the Dictionary's Keys collection, adding each key value to the lstKeys ListBox.
Next the program uses ToArray to convert the Dictionary's Values collection into an array. It then uses a for loop to loop through the array, adding each value to the lstValues ListBox. This kind of for loop will not work with the Values collection itself.
Finally the code uses a foreach loop to loop over the keys in the Dictionary's Keys collection. It uses the key values to index the Dictionary and displays each key and its corresponding value in the lstKeysAndValues ListBox.
Comments