#1,133 – Initializing a Dictionary with a Collection Initializer

You can initialize a generic Dictionary with a collection initializer as follows:

            // Initialization with collection initializer
            Dictionary<string, int> guys = new Dictionary<string,int> {
                    {"Galileo", 1564},
                    {"Magellan", 1480},
                    {"Voltaire", 1694},
                    {"Kepler", 1571},
                    {"Keaton", 1895}

            foreach (KeyValuePair<string, int> kvp in guys)
                Console.WriteLine("{0} ({1})", kvp.Key, kvp.Value);



#1,129 – Generic Dictionary Basics

The generic dictionary class, System.Collections.Generic.Dictionary<TKey,TValue>, allows you to store a collection of key/value pairs, where the both the keys and the values have a particular type.

You specify types for the keys and values when you declare an instance of the dictionary, creating a constructed type.  The example below creates an instance of a dictionary that stores an integer value for each of a set of character values.

            Dictionary<char, int> charCounter = new Dictionary<char, int>();

By default, the collection contains no entries–no key/value pairs.  You add an entry using the Add method, specifying a new key to be added, along with its value.  Note that the key is of type char and the value is of type int.

            charCounter.Add('x', 12);

If a dictionary already contains a particular key, you can retrieve the value using square bracket syntax.

            int numXs = charCounter['x'];