[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: List Dictionary keys and values in C#

[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) 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 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.