Dictionary in C#
C# has a class called "Dictionary" that can be used for many purposes. This tutorial shows how to declare, define, and initialize Dictionary in C# and how to use it in practice with code examples.
See more tutorials:
What is Dictionary in C#?
A C# Dictionary is an associative array that contains a set of keys and values. Dictionary cannot hold the same Key.
The following section shows you how to define a Dictionary in C# and how to use it.
How to define Dictionary in C#
This section describes the steps to declare, define, structure, and initialize a dictionary in C#.
Dictionary declaration
To use a Dictionary in C#, you need the following declaration:
using System.Collections.Generic;
The declaration of the Dictionary is as follows:
Dictionary<DataType, DataType> variable name = new Dictionary<DataType, DataType>();
The above declaration instantiates the Dictionary. The Dictionary must specify both the data type of Key and the data type of Value.
The following is a sample code that defines a Dictionary:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "dict" Dictionary<string, string> dict = new Dictionary<string, string>(); } } }
Dictionary and KeyValuePair structures
When dealing with a Dictionary in foreach, you can use the KeyValuePair structure to deal with the elements of the Dictionary in order. Below is a snippet of that code:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "students" Dictionary<string, string> students = new Dictionary<string, string>(); //Add elements students.Add("ID001", "James"); students.Add("ID002", "John"); students.Add("ID003", "Martin"); students.Add("ID004", "Mike"); // foreach (KeyValuePair<string, string> student in students) { Console.WriteLine("[ID: {0}, Name: {1}]", student.Key, student.Value); } } } }
Output:
[ID: ID001, Name: James]
[ID: ID002, Name: John]
[ID: ID003, Name: Martin]
[ID: ID004, Name: Mike]
Initializing Dictionary
Dictionary can be initialized in either of the following two patterns:
Dictionary<DataType, DataType> variable name = new Dictionary<DataType, DataType>() { {key1, value1}, {key2, value2}, ... };
Dictionary<DataType, DataType> variable name = new Dictionary<DataType, DataType> { {key1, value1}, {key2, value2}, ... };
The sample code that combines the declaration and initialization of the Dictionary is as follows:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize an empty dictionary Dictionary<int, string> dict1 = new Dictionary<int, string>(); //Instantiate and initialize at the same time Dictionary<int, string> dict2 = new Dictionary<int, string>() { {1, "A1"}, {2, "A2"}, {3, "A3"}, {4, "A4"}, }; //Instantiate and initialize at the same time Dictionary<int, string> dict3 = new Dictionary<int, string> { {1, "A1"}, {2, "A2"}, {3, "A3"}, {4, "A4"}, }; } } }
Basic usage of Dictionary
Once you have defined the Dictionary, the following sample code shows you the basic usage of the Dictionary:
Add an element with Add() method
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "dict" Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "Student 1"); students.Add("ID02", "Student 2"); students.Add("ID03", "Student 3"); students.Add("ID04", "Student 4"); } } }
If the same Key is already in the Dictionary, an error will occur when adding it.
Be aware that you cannot have more than one same Key in your code.
Fetching elements with foreach
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "dict" Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "Student 1"); students.Add("ID02", "Student 2"); students.Add("ID03", "Student 3"); students.Add("ID04", "Student 4"); Print(students); } static void Print(Dictionary<string, string> dictionary) { foreach (KeyValuePair<string, string> keyvaluepair in dictionary) { Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value); } } } }
Output:
[Key: ID01, Value: Student 1]
[Key: ID02, Value: Student 2]
[Key: ID03, Value: Student 3]
[Key: ID04, Value: Student 4]
With four elements added with the Add method, use foreach to retrieve the elements.
Getting Value by Key
Dictionary allows you to easily obtain Values using Keys. The following is an example of getting the paired Value by specifying "ID03" for Key:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "James"); students.Add("ID02", "Roland"); students.Add("ID03", "Mike"); students.Add("ID04", "Margin"); //Retrieve the value by specifying the key string value = students["ID03"]; Console.WriteLine("Value: {0}", value); } } }
The above execution result is as follows:
Value: Mike
You can confirm that the value "Mike" corresponding to "ID03" is obtained.
Removing elements with Remove() method
To add an element, we use the Add method.
To remove an element, we use the Remove() method. The following is a sample code that uses the Remove method:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "dict" Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "Student 1"); students.Add("ID02", "Student 2"); students.Add("ID03", "Student 3"); students.Add("ID04", "Student 4"); Console.WriteLine("Before removing:"); Print(students); //Remove one element students.Remove("ID03"); Console.WriteLine("After removing:"); Print(students); } static void Print(Dictionary<string, string> dictionary) { foreach (KeyValuePair<string, string> keyvaluepair in dictionary) { Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value); } } } }
Output:
Before removing:
[Key: ID01, Value: Student 1]
[Key: ID02, Value: Student 2]
[Key: ID03, Value: Student 3]
[Key: ID04, Value: Student 4]
After removing:
[Key: ID01, Value: Student 1]
[Key: ID02, Value: Student 2]
[Key: ID04, Value: Student 4]
Checking for the presence of elements
Use the containsKey method to check if a specified key is present.
The return value of the containsKey method is a boolean value.
Example:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "student" Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "Mike"); students.Add("ID02", "Roland"); students.Add("ID03", "Martin"); students.Add("ID04", "James"); // string key1 = "ID03"; Console.WriteLine("Check for {0}:", key1); if (students.ContainsKey(key1)) { Console.WriteLine("The key exists!"); } else { Console.WriteLine("The key does not exist!"); } string key2 = "ID05"; Console.WriteLine("Check for {0}:", key2); if (students.ContainsKey(key2)) { Console.WriteLine("The key exists!"); } else { Console.WriteLine("The key does not exist!"); } } } }
Output:
Check for ID03:
The key exists!
Check for ID05:
The key does not exist!
Use the containsValue method to determine if there is a specified value.
Example:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named "student" Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "James"); students.Add("ID02", "Roland"); students.Add("ID03", "Martin"); students.Add("ID04", "James"); students.Add("ID05", "Mike"); // string value1 = "John"; Console.WriteLine("Check for {0}:", value1); if (students.ContainsValue(value1)) { Console.WriteLine("The value exists!"); } else { Console.WriteLine("The value does not exist!"); } string value2 = "Roland"; Console.WriteLine("Check for {0}:", value2); if (students.ContainsValue(value2)) { Console.WriteLine("The value exists!"); } else { Console.WriteLine("The value does not exist!"); } } } }
Output:
Check for John:
The value does not exist!
Check for Roland:
The value exists!
Updating the value by specifying the key
The sample code shows how to update the value by specifying the key:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary class named students Dictionary<string, string> students = new Dictionary<string, string>() { {"ID01", "Student 1"}, {"ID02", "Student 2"}, {"ID03", "Student 3"}, {"ID04", "Student 4"} }; Console.WriteLine("Before updating:"); Print(students); //Update the value by key students["ID03"] = "Student 30"; Console.WriteLine("After updating:"); Print(students); } static void Print(Dictionary<string, string> dictionary) { foreach (KeyValuePair<string, string> keyvaluepair in dictionary) { Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value); } } } }
Output:
Before updating:
[Key: ID01, Value: Student 1]
[Key: ID02, Value: Student 2]
[Key: ID03, Value: Student 3]
[Key: ID04, Value: Student 4]
After updating:
[Key: ID01, Value: Student 1]
[Key: ID02, Value: Student 2]
[Key: ID03, Value: Student 30]
[Key: ID04, Value: Student 4]
How to make an element have multiple values
To have multiple values in a Dictionary element, you can have the Value part as a List.
Dictionary<TKey, List<TValue>> mDictionary = new Dictionary<TKey, List<TValue>>();
Example:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { //Initialize a dictionary Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>(); // string key1 = "001"; List<int> value1 = new List<int>(); value1.Add(100); value1.Add(101); //Add dict.Add(key1, value1); // string key2 = "002"; List<int> value2 = new List<int>(); value2.Add(100); value2.Add(101); value2.Add(102); //Add dict.Add(key2, value2); } } }
Copying a Dictionary
To easily copy a Dictionary, pass the source object as the constructor argument when declaring and defining the destination Dictionary.
Example:
using System; using System.Collections.Generic; namespace CSharpDictionary { class Program { static void Main(string[] args) { Dictionary<string, string> students = new Dictionary<string, string>(); //Add some elements students.Add("ID01", "James"); students.Add("ID02", "Roland"); students.Add("ID03", "Mike"); students.Add("ID04", "Martin"); //Print students Console.WriteLine("students:"); Print(students); //Copy Dictionary<string, string> students2 = new Dictionary<string, string>(students); Console.WriteLine("students2:"); Print(students2); //Modifiy vlaue students2["ID03"] = "Mike 2"; Console.WriteLine("students2 after modifying:"); Print(students2); } static void Print(Dictionary<string, string> dictionary) { foreach (KeyValuePair<string, string> keyvaluepair in dictionary) { Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value); } } } }
Output:
students:
[Key: ID01, Value: James]
[Key: ID02, Value: Roland]
[Key: ID03, Value: Mike]
[Key: ID04, Value: Martin]
students2:
[Key: ID01, Value: James]
[Key: ID02, Value: Roland]
[Key: ID03, Value: Mike]
[Key: ID04, Value: Martin]
students2 after modifying:
[Key: ID01, Value: James]
[Key: ID02, Value: Roland]
[Key: ID03, Value: Mike 2]
[Key: ID04, Value: Martin]
Summary
In this tutorial, you have learned how to declare, define, and initialize a dictionary in C#.
The feature of Dictionary is to handle Key and Value as a set; instead of an index number like List, you can retrieve the value by a key.
Refer to this article many times to get the most out of it.