The Dictionary type represents a collection of keys and values pair of data.
C# Dictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection.
Before you use the Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line.
using System.Collections.Generic;
Add Items to a Dictionary in C#
The Dictionary class constructor takes a key data type and a value data type. Both types are generic so it can be any .NET data type.
The following The Dictionary class is a generic class and can store any data types. This class is defined in the code snippet creates a dictionary where both keys and values are string types.
Dictionary<string, string> EmployeeList = new Dictionary<string, string>();
The following code snippet adds items to the dictionary.
EmployeeList.Add("SChand", "Programmer"); EmployeeList.Add("Praveen Kumar", "Project Manager");
EmployeeList.Add("Raj Kumar", "Architect");
EmployeeList.Add("Nipun Tomar", "Asst. Project Manager");
EmployeeList.Add("Dinesh Beniwal", "Manager");
The following code snippet creates a dictionary where the key type is string and value type is short integer.
Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
The following code snippet adds items to the dictionary.
AuthorList.Add("Susheel Kumar", 35);
AuthorList.Add("Raj Kumar", 25);
AuthorList.Add("Manish Kumar", 29);
AuthorList.Add("Raj Beniwal", 21);
AuthorList.Add("Dinesh Beniwal", 84);
Retrieve Items of a Dictionary in C#
The Dictionary is a collection. We can use the foreach loop to go through all the items and read them using they Key ad Value properties.
foreach (KeyValuePair<string, Int16> author in AuthorList)
{
Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
}
The following code snippet creates a new dictionary and reads all of its items and displays on the console.
public void CreateDictionary()
{
Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
AuthorList.Add("Susheel Kumar", 35);
AuthorList.Add("Ram Singh", 25);
AuthorList.Add("Praveen Kumar", 29);
AuthorList.Add("Raj Beniwal", 21);
AuthorList.Add("Dinesh Beniwal", 84);
// Read all data
Console.WriteLine("Authors List");
foreach (KeyValuePair<string, Int16> author in AuthorList)
{
Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
}
}