C# Generics Dictionary<K, V>


Generics Dictionary<K, V>

// 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();
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *