C# Tutorial For Beginners: Working with collections (Dictionaries)
Updated: Aug 22, 2021
The dictionary class is part of the “System.Collections.Generic” namespace. In this article, I will review this class and its main methods and properties. Before we dive into it, please note that each dictionary should receive two parameters before it can be used (Key Type, Type Value).
Static void Main (string [] args)
{
Dictionary<int, string> Names = new Dictionary<int, string>();
}
How to add data to a dictionary
static void Main(string[] args)
{
//Example #1: A dictionary with char as a key and bool as a value
Dictionary<int, string> WorkingWithDictionaries_1 = new Dictionary<int, string>();
WorkingWithDictionaries_1.Add(1,"Value 1");
WorkingWithDictionaries_1.Add(2,"Value 2");
//Example #2: A dictionary with an integer as a key and string as a value
Dictionary<char, bool> WorkingWithDictionaries_2 = new Dictionary<char, bool>();
WorkingWithDictionaries_2.Add('A', true);
WorkingWithDictionaries_2.Add('B', false);
}
How to read data from a dictionary
static void Main(string[] args)
{
Dictionary<int, string> WorkingWithDictionaries_1 = new Dictionary<int, string>();
WorkingWithDictionaries_1.Add(1, "Value_1");
WorkingWithDictionaries_1.Add(2, "Value_2");
WorkingWithDictionaries_1.Add(3, "Value_3");
// foreach (KeyValuePair<int, string> item in Names)
foreach (var item in WorkingWithDictionaries_1)
{
Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
}
}
Result
Key = 1, Value = Value_1
Key = 2, Value = Value_2
Key = 3, Value = Value_3
How to Remove dictionary data
We can remove all data of a dictionary or remove a specific value base on the use of specific commands:
static void Main(string[] args)
{
Dictionary<int, string> WorkingWithDictionaries_1 = new Dictionary<int, string>();
WorkingWithDictionaries_1.Add(1, "Value_1");
WorkingWithDictionaries_1.Add(2, "Value_2");
WorkingWithDictionaries_1.Add(3, "Value_3");
//Option 1: Remove a specific element
WorkingWithDictionaries_1.Remove(2);//Will remove "Value_2"
//Option 2: Clear all elements
WorkingWithDictionaries_1.Clear();
}
How to change a specific value in a Dictionary
This example will demonstrate how to modify a value based on a given key.
static void Main(string[] args)
{
Dictionary<string, int> NumberOfCitizens = new Dictionary<string, int>();
NumberOfCitizens.Add("London", 1000);
NumberOfCitizens.Add("Paris", 20000);
//To change the value of a key:
NumberOfCitizens["Tokyo"] = 5000;
}
The Contains Key Method
This code will demonstrate how to validate if a dictionary contains a specific key (Return False or True).
static void Main(string[] args)
{
Dictionary<string, int> NumberOfCitizens = new Dictionary<string, int>();
NumberOfCitizens.Add("London", 1000);
NumberOfCitizens.Add("Paris", 20000);
if (NumberOfCitizens.ContainsKey("London"))
{
Console.WriteLine("Key Available");
}
else
{
Console.WriteLine("Key Available:No");
}
}