C# Generics Dictionary<K, V>


This example is modified from the book Beginning C# 6 Programming with Visual Studio 2015 published by Wrox (A Wiley Brand) in 2016 written by Benjamin Perkins, Jacob Vibe Hammer and Jon D. Reid.

With Dictionary you can define a collection of key-value pairs.

// Generics - Dictionary<K, V>
// Written by Mike. namespace MikeDictionary
// Chapter 12, page 319
// Define a collection of key-value pairs
class Program  {
    static void Main(string[] args)  {
        Dictionary<string, int> things = new Dictionary<string, int>();
        things.Add("Green", 29);
        things.Add("Blue", 94);
        things.Add("Yellow", 34);
        WriteLine(things["Blue"]);  // output: 94
        foreach (string key in things.Keys) {
            WriteLine(key); } // output: Green Blue Yellow
        foreach (int value in things.Values) {
            WriteLine(value); } // output: 29 94 34
        foreach (KeyValuePair<string, int> thing in things) {
            WriteLine($"{thing.Key} = {thing.Value}"); } 
        // output: Green = 29 Blue = 94 Yellow = 34
        // Note: The key for each item must be unique; attempting to
        // add an item with an identical key will cause an 
        // ArguementException exception to be thrown
        ReadKey();
    }
}

Below we’ve added object initialization syntax. The output of the program will be the same.

using System;
using System.Collections.Generic;
namespace Dictionary2
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> things = new Dictionary<string, int>()
            {
                ["Green"] = 29,  // object intialization syntax
                ["Blue"]= 94
            };
            things.Add("Yellow", 34);
            Console.WriteLine(things["Blue"]);  // output: 94
            foreach (string key in things.Keys)
            {
                Console.WriteLine(key);
            } // output: Green Blue Yellow
            foreach (int value in things.Values)
            {
                Console.WriteLine(value);
            } // output: 29 94 34
            foreach (KeyValuePair<string, int> thing in things)
            {
                Console.WriteLine($"{thing.Key} = {thing.Value}");
            }
            // output: Green = 29 Blue = 94 Yellow = 34
            // Note: The key for each item must be unique; attempting to
            // add an item with an identical key will cause an 
            // ArguementException exception to be thrown
            Console.ReadKey();
        }
    }
}