In this article, I plan to give you an introduction to the dictionary collection. Dictionary can be defined as a data structure that holds key and value pairs together with no particular order. It is part of the System.Collections.Generic namespace. The key cannot be null and values can be empty or null. The key is also a unique entry whereas the values can have duplicates.
Table of Contents
Syntax of a Dictionary
Dictionary<TKey,TValue>
Dictionary is the keyword to refer to a dictionary.
TKey and TValue can be an object of any type.
Create a Dictionary
We can create a dictionary object by using the new operator. I will demonstrate a simple way to invoke a dictionary.
Dictionary<int, string> employeeDatabase = new Dictionary<int, string>();
//Declare and initialize the values from employeeDatabase
Dictionary<int, string> backupData = new Dictionary<int, string>(employeeDatabase);
Notice the new operator and an empty pair of parenthesis at the end to create a new object named employeeDatabase. We could copy contents from one dictionary to another by using another dictionary object instead of keeping it empty.
Adding elements to a dictionary
Lets see how we can add values into the dictionary. I have described an example below.
employeeDatabase.Add(1, "Nancy");
employeeDatabase.Add(2, "David");
employeeDatabase.Add(3, "Henry");
I have successfully added 3 new values to the database where the employee id is the key and the employee name is the value.
Lookup, Update and removal of the dictionary elements
Firstly, I have an example on how one can lookup or access the elements in the dictionary.
foreach(var item in employeeDatabase )
{
Console.WriteLine("Employee ID: "+item.Key.ToString()+" Emp Name: "+item.Value );
}
for (int i = 0; i < employeeDatabase.Count; i++)
{
Console.WriteLine(" Employee name and ID : " + employeeDatabase.ElementAt(i).Key + " " + employeeDatabase.ElementAt(i).Value);
}
We can access all the items one by one within a for loop and also the individual key and value elements in each item by using the above format. Another way to access them is by using the ElementAt index along with reference to a key or a value as per the example.
Secondly, We cannot update the key but we can update the value. I have an example for you. I updated the name of the employee for the key “5”.
employeeDatabase[5] = "Jeremy";
Console.WriteLine("Updated the fifth item to the name" + employeeDatabase[5]);
foreach (var item in employeeDatabase)
{
Console.WriteLine("Employee ID: " + item.Key.ToString() + " Emp Name: " + item.Value);
}
Thirdly, We can remove an element at an index. This will remove both the key and value. An example is as follows.
//Removing the element
employeeDatabase.Remove(4);
Console.WriteLine("After removing 4");
foreach (var item in employeeDatabase)
{
Console.WriteLine("Employee ID: " + item.Key.ToString() + " Emp Name: " + item.Value);
}
Properties of a dictionary: Count, keys, values
Some of the queries like count, keys, and values are very useful. Count retrieves the total number of elements in the dictionary. Keys will all the keys in the dictionary which can be iterated over or converted to a list. Lastly, we can also use values to iterate over or to be converted into a list. The examples are shown below.
Console.WriteLine("There are " + employeeDatabase.Count + "elements in the dictionary");
Console.WriteLine("Keys ");
foreach (int key in employeeDatabase.Keys)
{
Console.WriteLine(key);
}
Console.WriteLine("Values\n");
foreach(string val in employeeDatabase.Values)
{
Console.WriteLine(val);
}
Complete example
I have aggregated all the mini examples into one. Feel free to try this program.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TelestreakTutorial
{
class Program
{
static void DictionaryTutorial()
{
Dictionary<int, string> employeeDatabase = new Dictionary<int, string>();
employeeDatabase.Add(1, "Nancy");
employeeDatabase.Add(2, "David");
employeeDatabase.Add(3, "Henry");
employeeDatabase.Add(4, "Beth");
employeeDatabase.Add(5, "James");
foreach(var item in employeeDatabase )
{
Console.WriteLine("Employee ID: "+item.Key.ToString()+" Emp Name: "+item.Value );
}
Console.WriteLine("Another way of accessing elements");
for (int i = 0; i < employeeDatabase.Count; i++)
{
Console.WriteLine(" Employee name and ID : " + employeeDatabase.ElementAt(i).Key + " " + employeeDatabase.ElementAt(i).Value);
}
employeeDatabase[5] = "Jeremy";
Console.WriteLine("Updated the fifth item to the name" + employeeDatabase[5]);
foreach (var item in employeeDatabase)
{
Console.WriteLine("Employee ID: " + item.Key.ToString() + " Emp Name: " + item.Value);
}
//Removing the element
employeeDatabase.Remove(4);
Console.WriteLine("After removing 4");
foreach (var item in employeeDatabase)
{
Console.WriteLine("Employee ID: " + item.Key.ToString() + " Emp Name: " + item.Value);
}
Console.WriteLine("There are " + employeeDatabase.Count + "elements in the dictionary");
Console.WriteLine("Keys ");
foreach (int key in employeeDatabase.Keys)
{
Console.WriteLine(key);
}
Console.WriteLine("Values\n");
foreach(string val in employeeDatabase.Values)
{
Console.WriteLine(val);
}
return;
}
static void Main(string[] args)
{
DictionaryTutorial();
}
}
}
Conclusion
In conclusion, we learn about the most commonly used methods and properties in a dictionary. Feel free to try them.
Next: Coming soon