Dot Net Perls
C#

Dictionary Keys and Values

by Sam Allen

Problem

Check or display each key and value in Dictionary using KeyValuePair and foreach. This will allow us to examine or display all items in the Dictionary. We must have the most efficient way possible, and also the most graceful and simplest.

Solution: C#

The most efficient method is not actually in many books on C#, and resources are scarce elsewhere. When Dictionary, or any object that implements IDictionary, is used in a foreach loop, it returns an enumeration. In the case of Dictionary, this enumeration is in the form of a KeyValuePair instances.

KeyValuePair member Use
Key The lookup key in the pair
pair.Key
Value The value in the pair
(contains the contents of the entry)
pair.Value

How can I use foreach on Dictionary?

We must use traditional foreach syntax and declare a new KeyValuePair in the foreach loop. With generics like Dictionary, we must always know the value types. With each KeyValuePair, there are two important members, which I show after this.

static void Main(string[] args)
{
    Dictionary<string, int> stringDict = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };
    ShowDictionaryPair(stringDict);
}

/// <summary>
/// Display all the keys and their values in the dictionary.
/// </summary>
/// <param name="stringDict">The dictionary to examine.</param>
static void ShowDictionaryPair(Dictionary<string, int> stringDict)
{
    foreach (KeyValuePair<string, int> pair in stringDict)
    {
        Console.WriteLine(pair.Key + ", " + pair.Value.ToString());
    }
    // cat, 2
    // dog, 1
    // llama, 0
    // iguana, -1
}

How can I get all the keys?

There is another way to find all the keys and print all their values in a Dictionary. This method retrieves a list of Keys from that property, and then looks through each key and gets the value. This method is much slower but has the same results. Using the Keys collection and putting them in an array or List is very effective in other situations.

/// <summary>
/// Display all the keys and values in the dictionary.
/// </summary>
/// <param name="stringDict">The dictionary to check.</param>
static void ShowDictionaryKeys(Dictionary<string, int> stringDict)
{
    foreach (string keyItem in stringDict.Keys.ToArray())
    {
        Console.WriteLine(keyItem + ", " + stringDict[keyItem].ToString());
    }
}

How much faster is KeyValuePair?

About 3 times faster than the second method shown right above. This is probably because an array copy is not needed and the Keys collection is not used. KeyValuePair allows us to simply look through each pair one at a time. This avoids copying and using the garbage-collected heap for storage.

Version Time in ms
1 million tests
KeyValuePair
First method shown
125
Keys array
Second method
437

Summary

Use KeyValuePair for a fast and precise way of checking all keys and finding all their values in the Dictionary. Use this approach to convert Dictionary to strings. Generics avoid casting and boxing/unboxing. Other structures, like SortedList, can be used. Read more on doing Dictionary lookups in the best way.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge