4.2 Dictionaries

In C#, a dictionary is similar to Webster's dictionary. The C# dictionary is similar by using a collection of Keys and Values, where the key is like a word and the value is like a definition.

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it Dictionaries

Visualization

Add the following code to the Program.cs file to practice dictionaries:

    class Program
    {
        static void Main(string[] args)
        {
//          1             2            3     4
            IDictionary<int, string> dict = new Dictionary<int, string>();
//           5     6    7
            dict.Add(1,"One");
            dict.Add(2,"Two");
            dict.Add(3,"Three");
        }
    }
  1. Declaring that you are building a dictionary

  2. The parameter types for your dictionary. A related int and string value

  3. The name of your dictionary

  4. Instantiation of a new dictionary

  5. Accessing your dictionary by just typing the name

  6. Using the .Add() function to begin adding data to your dictionary

  7. Key/Value pairs you are adding to your dictionary

Discussion

Dictionary<TKey, TValue> is a generic collection included in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of value.

Dictionary Initialization

A dictionary can be initialized with a variable of IDictionary<Tkey, TValue> or Dictionary<TKey, TValue>

IDictionary<int, string> dict = new Dictionary<int, string>();

or

Dictionary<int, string> dict = new Dictionary<int, string>();

In the above example, we have specified types of key and value while declaring a dictionary object. An int is a type of key and string is a type of value that will be stored into a dictionary object named dict. You can use any valid C# data type for keys and values.

Another Example

Add the following code to your Program.cs file:

 class Program
    {
        static void Main(string[] args)
        {
            IDictionary<string, string> goldenGirls = new Dictionary<string, string>();
            goldenGirls.Add("Rose", "Sweet");
            goldenGirls.Add("Dorothy", "Sharp");
            goldenGirls.Add("Blanche", "Southern");
            goldenGirls.Add("Sophia", "Sassy");

            foreach (KeyValuePair<string, string> pair in goldenGirls)
            {
                Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
            }
        }
    }

We made a dictionary called goldenGirls and added 4 elements to it with a string key and string value. Then printed each key/value pair to the console using a for each loop.

Challenges:

Bronze

  • Create a dictionary of your top five TV shows as your key and your favorite character as the value

Silver

  • Create a dictionary that uses arrays for the values

Gold

  • Use the previous dictionary and print the key/valur pairs

    Answers

Next: Lists

Last updated