List Dictionary keys and values in C#


A Dictionary object’s Keys property is a KeyCollection containing the dictionary’s keys. Similarly, its Values property is a ValueCollection containing the dictionary’s values. 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 their values into normal arrays.

This example uses the following code to initialize a Dictionary.

// The dictionary of digit names.
private Dictionary<int, string> Numbers =
    new Dictionary<int, string>()
    {0, "Zero"},
    {1, "One"},
    {2, "Two"},
    {3, "Three"},
    {4, "Four"},
    {5, "Five"},
    {6, "Six"},
    {7, "Seven"},
    {8, "Either"},
    {9, "Nine"}

The form’s Load event handler then uses the following code to display the Dictionary object’s keys, values, and key/value pairs.

private void Form1_Load(object sender, EventArgs e)
    // Display the keys.
    foreach (int number in Numbers.Keys)

    // 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++)

    // 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 object’s Keys collection, adding each key value to the ListBox named lstKeys.

Next, the program uses ToArray to convert the Dictionary object’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 iterate over the keys in the Dictionary object’s Keys collection. It uses the key values as indices into the Dictionary and displays each key and its corresponding value in the lstKeysAndValues ListBox.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, controls, lists and tagged , , , , , , , , , , , , . Bookmark the permalink.

1 Response to List Dictionary keys and values in C#

  1. Hiral says:


    Thank you for sharing this article really helped me better understand dictionaries and how to manipulate them. I found another similar tutorial, c# loop through dictionary that I think is a good compliment to this. Let me know what you think!


Comments are closed.