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.

arun kumar vermaPosted Mar 1, 2024, 5:08 PM
Error: There is no Get method in the Dictionary class in C#. Need to use the [] index to access values by keys. from int value = dictionary.Get("one"); to int value = dictionary["one"];
Harun OconnellPosted Feb 1, 2023, 9:30 PM
Class Battalion { private Dictionary<int, Soldier> soldiers; public Battalion() { soldiers = new Dictionary<int, Soldier>(); } public void AddSoldier(int id, Soldier soldier) { soldiers.Add(id, soldier); } public void RemoveSoldier(int id) { soldiers.Remove(id); } public void DisplaySoldiers() { Console.WriteLine("List of soldiers:"); foreach (var soldier in soldiers) { Console.WriteLine("ID: " + soldier.Key + ", Name: " + soldier.Value.Name); } }
Harun OconnellPosted Feb 1, 2023, 9:25 PM
Aby dodac nowy slownik z kluczem id w C#, mozna uzyc Dictionary<int, Soldier>, gdzie int jest kluczem, a Soldier jest typem wartosci. Aby dodac nowy zolnierz, mozna uzyc metody Add (klucz, wartosc), aby usunac mozna uzyc metody Remove (klucz), a sortowanie mozna wykonac przy uzyciu metody OrderBy (x => x.Value.Nazwisko).
onyango ogollaPosted Feb 2, 2022, 7:17 PM
Great read, also introduce the lambda expressions especially in functions eg dictionarObject.OrderBy(x => x.key);
prithvi dheerPosted Oct 3, 2021, 5:57 PM
Great it saved my interview, Thank you Mahesh sir
Pankajkumar PatelPosted Aug 22, 2019, 3:59 AM
Nice article
Chriso ViduaPosted Apr 6, 2019, 2:53 AM
Hi, i created three dictionaries (dict1, dict2 and dict3), i would like to merge the dict1 and dict2 into dict3, but the concern is that i have to check the dictionaries (dict1 and dict2) before adding it in dict3. that's where I get stuck, when I try to add with "foreach", I have a "double key" error because some of dict1's elements are in dict2. so am obliged to check before adding them to the dict3. I need to help ..... thanks
Chriso ViduaPosted Apr 6, 2019, 2:53 AM
Salut, j'ai cr?e trois dictionnaires(dict1,dict2 et dict3), j'aimerais fusionner le dict1 et dict2 dans dict3, mais le souci est que je dois verifier les dictionnaires(dict1 et dict2) avant de le ajouter dans dict3. c'est l? que suis bloqu?, lorque j'essai d'ajouter avec "foreach" , j'ai une erreur <<cl? double>> parce que certains ?l?ment de dict1 se trouvent dans dict2. donc suis oblig? de v?rifier avant de les ajouter dans le dict3. j'ai besoin d'aider..... merci
Arjun DhilodPosted Dec 16, 2018, 1:24 PM
Very nice all in one
Alice NguyenPosted Dec 3, 2018, 4:20 AM
Great, for sharing thank Mahesh.
Amit Kumar SinghPosted Nov 29, 2018, 3:55 AM
Thanks for sharing Mahesh Sir!!!
Mohd ArifPosted Aug 22, 2017, 12:46 AM
Why we need dictionary in C#? Please Explain in a real example
Sailaja KamineniPosted Sep 22, 2014, 11:02 AM
Thank you so much Mahesh Chand. Very userful infromation.
Mahesh ChandPosted Aug 12, 2012, 10:41 AM
Hi Cristian Solervicens, You could also extend an article if it is related topic. Cheers!
Cristian SolervicensPosted Apr 8, 2011, 2:11 PM
Something important about flexibility of the Dictionary is that it accepts user defined classes as elements. class MyClass { public string atrib1 { get; set; } public int natrib { get; set; } } I can do MyClass Klase = new MyClass(); Dictionary<string, MyClass> Dict = new Dictionary<string, MyClass>(); Klase.atrib1 = "Primero"; Klase.natrib = 1; Dict.Add("Primero", Klase); //I Can acces the elements like this... "Secure Way" If don't exists, don't rise error. if (Dict.TryGetValue("Segundo", out Klase)) Console.WriteLine("Encontró {0}, {1}", Klase.atrib1, Klase.natrib); //I Can acces the elements like this... "INSecure Way" If don't exists it rises an error. Console.WriteLine("Encontró {0}, {1}", Dict["Segundo"].atrib1, Dict["Segundo"].natrib); //I can navigate through the Dictionary like this foreach (var p in Dict) { Console.WriteLine("Recorro {0}, {1}", p.Value.atrib1 , p.Value.natrib ); }
Shiraz KhaneditedPosted Mar 10, 2011, 2:00 PMEdited Mar 11, 2011, 1:09 AM
Dear Sir, i want your help regarding Singleton Pattern.. actually i m beginner programmer so i want to Create Multiple Objects in Singleton Pattern and restricted to 4 length...means after the creation of 4th object it will generate some error msg when user try to create 5th object...i still finding on the net but didn't find any example related to my problem ..i m very great thankful to you..if you make just simple program for me which resolve my problem ...