Most Common C# Dictionary Code Examples

Most common C# Dictionary code examples.

C# Dictionary class is a generic collection of keys and values pair of data. The 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.

  1. using System.Collections.Generic;  

1. 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 it can be any .NET data type.

The following 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.

  1. Dictionary<stringstring> EmployeeList = new Dictionary<stringstring>();

The following code snippet adds items to the dictionary.

  1. EmployeeList.Add("Mahesh Chand""Programmer");    
  2. EmployeeList.Add("Praveen Kumar""Project Manager");    
  3. EmployeeList.Add("Raj Kumar""Architect");    
  4. EmployeeList.Add("Nipun Tomar""Asst. Project Manager");    
  5. EmployeeList.Add("Dinesh Beniwal""Manager");    

The following code snippet creates a dictionary where the key type is string and value type is short integer.

  1. Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
The following code snippet adds items to the dictionary. 
  1. AuthorList.Add("Mahesh Chand", 35);    
  2. AuthorList.Add("Mike Gold", 25);    
  3. AuthorList.Add("Praveen Kumar", 29);    
  4. AuthorList.Add("Raj Beniwal", 21);    
  5. 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 string and value type is float and total number of items it can hold is 3.

  1. Dictionary<stringfloat> PriceList = new Dictionary<stringfloat>(3);   

The following code snippet adds items to the dictionary.

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

2. Retrieve elements from a C# Dictionary

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. 

  1. foreach (KeyValuePair<string, Int16> author in AuthorList)    
  2. {    
  3.     Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);    
  4. }

The following code snippet creates a new dictionary and reads all of its items and displays on the console.

  1. public void CreateDictionary()    
  2. {    
  3.     // Create a dictionary with string key and Int16 value pair    
  4.     Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();    
  5.     AuthorList.Add("Mahesh Chand", 35);    
  6.     AuthorList.Add("Mike Gold", 25);    
  7.     AuthorList.Add("Praveen Kumar", 29);    
  8.     AuthorList.Add("Raj Beniwal", 21);    
  9.     AuthorList.Add("Dinesh Beniwal", 84);    
  10.     // Read all data    
  11.     Console.WriteLine("Authors List");    
  12.     foreach (KeyValuePair<string, Int16> author in AuthorList)    
  13.     {    
  14.         Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);    
  15.     }    
  16. }    
  17.    

3. C# Dictionary Properties

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

4. Get number of elements in a C# dictionary

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

The following code snippet display number of items in a dictionary.

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

5. Get a Dictionary item 

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

The following code snippet sets and gets an items value.

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

6. Get the collection of keys of 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. 

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

7. 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.

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

8. 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. 

9. Add Items 

The Add method adds an item to the Dictionary collection in form of a key and a value. 

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

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

Alternatively, we can use the Item property. If the key does not exist in the collection, a new item is added. 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.

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

10. 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. 

  1. // Remove item with key = 'Mahesh Chand'    
  2. 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.

  1. // Remove all items    
  2. AuthorList.Clear();

11. Find a Key in a Dictionary

The ContainsKey method checks if a key is already exists in the dictionary. The following code snippet checks if a key is already exits and if not, add one.

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

12. Find a Value in a Dictionary

The ContainsValue method checks if a value is already exists in the dictionary. The following code snippet checks if a value is already exits.

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

13. C# Dictionary Code Example 

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

  1. // Create a dictionary with string key and Int16 value pair    
  2. Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();    
  3. AuthorList.Add("Mahesh Chand", 35);    
  4. AuthorList.Add("Mike Gold", 25);    
  5. AuthorList.Add("Praveen Kumar", 29);    
  6. AuthorList.Add("Raj Beniwal", 21);    
  7. AuthorList.Add("Dinesh Beniwal", 84);    
  8. // Count    
  9. Console.WriteLine("Count: {0}", AuthorList.Count);    
  10. // Set Item value    
  11. AuthorList["Neel Beniwal"] = 9;    
  12. if (!AuthorList.ContainsKey("Mahesh Chand"))    
  13. {    
  14.     AuthorList["Mahesh Chand"] = 20;    
  15. }    
  16. if (!AuthorList.ContainsValue(9))    
  17. {    
  18.     Console.WriteLine("Item found");    
  19. }    
  20.     
  21. // Read all items    
  22. Console.WriteLine("Authors all items:");    
  23. foreach (KeyValuePair<string, Int16> author in AuthorList)    
  24. {    
  25.     Console.WriteLine("Key: {0}, Value: {1}",    
  26.     author.Key, author.Value);    
  27. }    
  28. // Remove item with key = 'Mahesh Chand'    
  29. AuthorList.Remove("Mahesh Chand");    
  30. // Remove all items    
  31. AuthorList.Clear();  

14. Summary

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