Introduction
Dictionaries are a data structure where a key/value pairs are stored. There are some rules for dictionaries:
-
Keys in dictionaries must be unique. You cannot have duplicate keys. You can have duplicate values.
-
Keys cannot be null. Values can be null.
-
Only elements of the same type can be stored in a dictionary.
-
A dictionary’s capacity depends on how many elements a dictionary has the capability of holding.
Structure of a dictionary
The structure of a dictionary is as follows:
Dictionary<Tkey, TValue>
Creating a dictionary
In order to create a dictionary, we first need to import the appropriate namespace:
using System.Collections.Generic;
Let’s say we want to create a dictionary that has keys of type int
and values of type string
. This is how we do it:
Dictionary<int,string> users = new Dictionary<int,string>();
//Shorthand
var users = new Dictionary<int,string>();
Inserting data into a dictionary
In order to insert data into a dictionary, we use the Add
method:
users.Add(1, "Sys Admin");
users.Add(2, "Network Admin");
users.Add(3, "grahamb");
users.Add(4, "petersonj");
Checking for a key in a dictionary
If we want to find if a particular key is in a dictionary, we use the ContainsKey
method:
Console.WriteLine(users.ContainsKey(4)); //True
Checking for a value in a dictionary
If on the other hand, we want to find a value, we use the ContainsValue
method:
Console.WriteLine(users.ContainsValue("petersonj")); //True
Removing data from a dictionary
In order to remove data from a dictionary, we use the Remove
method along with the key:
Console.WriteLine(users.Remove(1)); //True
Clearing a dictionary
If we want to clear the entire dictionary, we use the Clear
method:
users.Clear();