Dictionary In C#

A C# dictionary is a generic collection of key-value pairs. The keys must be unique, but the values can be duplicated. Dictionaries are implemented as hash tables so their keys can quickly access them.

To create a dictionary in C#, you use the Dictionary<TKey, TValue> class, where TKey is the type of the keys, and TValue is the type of the values. For example, the following code creates a dictionary that can store strings as keys and integers as values:

Dictionary<string, int> dictionary = new Dictionary<string, int>();

You can add key-value pairs to a dictionary using the Add() method. For example, the following code adds two key-value pairs to the dictionary:

dictionary.Add("one", 1);
dictionary.Add("two", 2);

You can retrieve a value from a dictionary by its key using the Get() method. For example, the following code retrieves the value associated with the key "one":

int value = dictionary.Get("one");

You can also iterate over the keys or values in a dictionary using the Keys() or Values() methods. For example, the following code iterates over the keys in the dictionary and prints them to the console:

foreach (string key in dictionary.Keys())
{
    Console.WriteLine(key);
}

Here are some of the advantages of using dictionaries in C#:

  • They are very efficient for accessing values by their keys.
  • They can be used to store a large number of key-value pairs.
  • They are easy to use and manage.

Here are some of the disadvantages of using dictionaries in C#:

  • They can be slow for iterating over all the key-value pairs.
  • They can be memory-intensive if they store a large number of key-value pairs.

Here are some examples of when you might use a dictionary in C#:

  • To store a mapping of names to phone numbers.
  • To store a mapping of countries to capital cities.
  • To store a mapping of words to their definitions.
  • To store a mapping of user IDs to user profiles.
  • To store a mapping of product IDs to product prices.

C# Dictionary class is a generic collection of keys and values pair of data. The Dictionary class is defined in the System.Collections.A generic namespace is a class that can store any data type in 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; 

How to Add Elements to a C# Dictionary?

C# Dictionary class constructor takes a key data type and a value data type. Both types are generic, so they can be any .NET data type.

The following Dictionary class is a generic class and can store any data type. This class is defined in the code snippet and 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("Mahesh Chand", "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 a string, and the value type is a short integer.

Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  

The following code snippet adds items to the Dictionary. 

AuthorList.Add("Mahesh Chand", 35);    
AuthorList.Add("Mike Gold", 25);    
AuthorList.Add("Praveen Kumar", 29);    
AuthorList.Add("Raj Beniwal", 21);    
AuthorList.Add("Dinesh Beniwal", 84);    

We can also limit the size of a dictionary. The following code snippet creates a dictionary where the key type is a string, the value type is float, and the total number of items it can hold is 3.

Dictionary<string, float> PriceList = new Dictionary<string, float>(3);

The following code snippet adds items to the Dictionary.

PriceList.Add("Tea", 3.25f);    
PriceList.Add("Juice", 2.76f);    
PriceList.Add("Milk", 1.15f);    

How to Retrieve Elements from a C# Dictionary?

The Dictionary is a collection. So, we can use the foreach loop to go through all the items and read them using the 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, reads all its items, and displays them on the console.

public void CreateDictionary()    
{    
    // Create a dictionary with string key and Int16 value pair    
    Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();    
    AuthorList.Add("Mahesh Chand", 35);    
    AuthorList.Add("Mike Gold", 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);    
    }    
}    

C# Dictionary Properties

The Dictionary class has three properties – Count, Keys, and Values.

How do you get the number of elements in a C# dictionary?

The Count property gets the number of key/value pairs in a dictionary. 

The following code snippet displays the number of items in a dictionary.

Console.WriteLine("Count: {0}", AuthorList.Count);

How to get an item from a C# dictionary?

The Item property gets and sets the value associated with the specified key. 

The following code snippet sets and gets the value of an item.

// Set Item value    
AuthorList["Mahesh Chand"] = 20;    
// Get Item value    
Int16 age = Convert.ToInt16(AuthorList["Mahesh Chand"]);    

How do you get a collection of keys in a C# dictionary?

The Keys property gets a collection containing the keys in the Dictionary. It returns an object of KeyCollection type. 

The following code snippet reads all keys in a Dictionary. 

// Get and display keys    
Dictionary<string, Int16>.KeyCollection keys = AuthorList.Keys;    
foreach (string key in keys)    
{    
    Console.WriteLine("Key: {0}", key);    
}

How to get the collection of values of a C# dictionary?

The Values property gets a collection containing the values in the Dictionary. It returns an object of ValueCollection type. 

The following code snippet reads all values in a Dictionary.

// Get and display values    
Dictionary<string, Int16>.ValueCollection values = AuthorList.Values;    
foreach (Int16 val in values)    
{    
    Console.WriteLine("Value: {0}", val);
}

C# Dictionary Methods

The Dictionary class is a generic collection and provides all common methods to add, remove, find, and replace items in the collection. 

How to add items to a C# dictionary?

The Add method adds an item to the Dictionary collection as a key and a value. 

The following code snippet creates a Dictionary and adds an item using the Add method. 

Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();    
AuthorList.Add("Mahesh Chand", 35);

Alternatively, we can use the Item property. A new item is added if the key is not in the collection. If the same key already exists in the collection, the item value is updated to the new value. 

The following code snippet adds an item and updates the existing item in the collection.

AuthorList["Neel Beniwal"] = 9;    
AuthorList["Mahesh Chand"] = 20;

How to remove elements from a C# dictionary?

The Remove method removes an item with the specified key from the collection. The following code snippet removes an item. 

// Remove item with key = 'Mahesh Chand'    
AuthorList.Remove("Mahesh Chand");

The Clear method removes all items from the collection. The following code snippet removes all items by calling the Clear method.

// Remove all items    
AuthorList.Clear();

How to find a key in a dictionary?

The ContainsKey method checks if a key already exists in the Dictionary. The following code snippet checks if a key already exists; if not, add one.

if (!AuthorList.ContainsKey("Mahesh Chand"))    
{    
    AuthorList["Mahesh Chand"] = 20;    
}

How to find a value in a dictionary?

The ContainsValue method checks if a value already exists in the Dictionary. The following code snippet checks if a deal is already exited.

if (!AuthorList.ContainsValue(9))    
{    
    Console.WriteLine("Item found");    
}

C# Dictionary Code Example 

Here is the complete sample code showing how to use these methods. 

// Create a dictionary with string key and Int16 value pair    
Dictionary < string, Int16 > AuthorList = new Dictionary < string, Int16 > ();
AuthorList.Add("Mahesh Chand", 35);
AuthorList.Add("Mike Gold", 25);
AuthorList.Add("Praveen Kumar", 29);
AuthorList.Add("Raj Beniwal", 21);
AuthorList.Add("Dinesh Beniwal", 84);
// Count    
Console.WriteLine("Count: {0}", AuthorList.Count);
// Set Item value    
AuthorList["Neel Beniwal"] = 9;
if (!AuthorList.ContainsKey("Mahesh Chand")) {
AuthorList["Mahesh Chand"] = 20;
}
if (!AuthorList.ContainsValue(9)) {
Console.WriteLine("Item found");
}
// Read all items    
Console.WriteLine("Authors all items:");
foreach(KeyValuePair < string, Int16 > author in AuthorList) {
Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
}
// Remove item with key = 'Mahesh Chand'    
AuthorList.Remove("Mahesh Chand");
// Remove all items    
AuthorList.Clear();

Summary

In this tutorial, we learned about the basic use of a dictionary using C# language. We also learned how to create a dictionary using the C# and .NET Dictionary class. After that, we learned how to use various methods and properties of the class. 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.