C# Dictionary with Examples

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "dict"
  10. Dictionary<string, string> dict = new Dictionary<string, string>();
  11. }
  12. }
  13. }
  14.  

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "students"
  10. Dictionary<string, string> students = new Dictionary<string, string>();
  11. //Add elements
  12. students.Add("ID001", "James");
  13. students.Add("ID002", "John");
  14. students.Add("ID003", "Martin");
  15. students.Add("ID004", "Mike");
  16. //
  17. foreach (KeyValuePair<string, string> student in students)
  18. {
  19. Console.WriteLine("[ID: {0}, Name: {1}]", student.Key, student.Value);
  20. }
  21. }
  22. }
  23. }
  24.  

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize an empty dictionary
  10. Dictionary<int, string> dict1 = new Dictionary<int, string>();
  11.  
  12. //Instantiate and initialize at the same time
  13. Dictionary<int, string> dict2 = new Dictionary<int, string>()
  14. {
  15. {1, "A1"},
  16. {2, "A2"},
  17. {3, "A3"},
  18. {4, "A4"},
  19. };
  20. //Instantiate and initialize at the same time
  21. Dictionary<int, string> dict3 = new Dictionary<int, string>
  22. {
  23. {1, "A1"},
  24. {2, "A2"},
  25. {3, "A3"},
  26. {4, "A4"},
  27. };
  28. }
  29. }
  30. }

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

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "dict"
  10. Dictionary<string, string> students = new Dictionary<string, string>();
  11. //Add some elements
  12. students.Add("ID01", "Student 1");
  13. students.Add("ID02", "Student 2");
  14. students.Add("ID03", "Student 3");
  15. students.Add("ID04", "Student 4");
  16. }
  17. }
  18. }

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

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "dict"
  10. Dictionary<string, string> students = new Dictionary<string, string>();
  11. //Add some elements
  12. students.Add("ID01", "Student 1");
  13. students.Add("ID02", "Student 2");
  14. students.Add("ID03", "Student 3");
  15. students.Add("ID04", "Student 4");
  16. //Print
  17. Print(students);
  18. }
  19. static void Print(Dictionary<string, string> dictionary)
  20. {
  21. foreach (KeyValuePair<string, string> keyvaluepair in dictionary)
  22. {
  23. Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value);
  24. }
  25. }
  26. }
  27. }

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Dictionary<string, string> students = new Dictionary<string, string>();
  10. //Add some elements
  11. students.Add("ID01", "James");
  12. students.Add("ID02", "Roland");
  13. students.Add("ID03", "Mike");
  14. students.Add("ID04", "Margin");
  15. //Retrieve the value by specifying the key
  16. string value = students["ID03"];
  17. //Print
  18. Console.WriteLine("Value: {0}", value);
  19. }
  20. }
  21. }

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "dict"
  10. Dictionary<string, string> students = new Dictionary<string, string>();
  11. //Add some elements
  12. students.Add("ID01", "Student 1");
  13. students.Add("ID02", "Student 2");
  14. students.Add("ID03", "Student 3");
  15. students.Add("ID04", "Student 4");
  16. //Print
  17. Console.WriteLine("Before removing:");
  18. Print(students);
  19. //Remove one element
  20. students.Remove("ID03");
  21. //Print
  22. Console.WriteLine("After removing:");
  23. Print(students);
  24. }
  25. static void Print(Dictionary<string, string> dictionary)
  26. {
  27. foreach (KeyValuePair<string, string> keyvaluepair in dictionary)
  28. {
  29. Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value);
  30. }
  31. }
  32. }
  33. }
  34.  

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "student"
  10. Dictionary<string, string> students = new Dictionary<string, string>();
  11. //Add some elements
  12. students.Add("ID01", "Mike");
  13. students.Add("ID02", "Roland");
  14. students.Add("ID03", "Martin");
  15. students.Add("ID04", "James");
  16. //
  17. string key1 = "ID03";
  18. Console.WriteLine("Check for {0}:", key1);
  19. if (students.ContainsKey(key1))
  20. {
  21. Console.WriteLine("The key exists!");
  22. }
  23. else
  24. {
  25. Console.WriteLine("The key does not exist!");
  26. }
  27. string key2 = "ID05";
  28. Console.WriteLine("Check for {0}:", key2);
  29. if (students.ContainsKey(key2))
  30. {
  31. Console.WriteLine("The key exists!");
  32. }
  33. else
  34. {
  35. Console.WriteLine("The key does not exist!");
  36. }
  37. }
  38. }
  39. }
  40.  

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named "student"
  10. Dictionary<string, string> students = new Dictionary<string, string>();
  11. //Add some elements
  12. students.Add("ID01", "James");
  13. students.Add("ID02", "Roland");
  14. students.Add("ID03", "Martin");
  15. students.Add("ID04", "James");
  16. students.Add("ID05", "Mike");
  17. //
  18. string value1 = "John";
  19. Console.WriteLine("Check for {0}:", value1);
  20. if (students.ContainsValue(value1))
  21. {
  22. Console.WriteLine("The value exists!");
  23. }
  24. else
  25. {
  26. Console.WriteLine("The value does not exist!");
  27. }
  28. string value2 = "Roland";
  29. Console.WriteLine("Check for {0}:", value2);
  30. if (students.ContainsValue(value2))
  31. {
  32. Console.WriteLine("The value exists!");
  33. }
  34. else
  35. {
  36. Console.WriteLine("The value does not exist!");
  37. }
  38. }
  39. }
  40. }

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary class named students
  10. Dictionary<string, string> students =
  11. new Dictionary<string, string>() {
  12. {"ID01", "Student 1"},
  13. {"ID02", "Student 2"},
  14. {"ID03", "Student 3"},
  15. {"ID04", "Student 4"}
  16. };
  17. //Print
  18. Console.WriteLine("Before updating:");
  19. Print(students);
  20. //Update the value by key
  21. students["ID03"] = "Student 30";
  22. //Print
  23. Console.WriteLine("After updating:");
  24. Print(students);
  25. }
  26. static void Print(Dictionary<string, string> dictionary)
  27. {
  28. foreach (KeyValuePair<string, string> keyvaluepair in dictionary)
  29. {
  30. Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value);
  31. }
  32. }
  33. }
  34. }

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:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initialize a dictionary
  10. Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
  11. //
  12. string key1 = "001";
  13. List<int> value1 = new List<int>();
  14. value1.Add(100);
  15. value1.Add(101);
  16. //Add
  17. dict.Add(key1, value1);
  18. //
  19. string key2 = "002";
  20. List<int> value2 = new List<int>();
  21. value2.Add(100);
  22. value2.Add(101);
  23. value2.Add(102);
  24. //Add
  25. dict.Add(key2, value2);
  26. }
  27. }
  28. }
  29.  

Copying a Dictionary

To easily copy a Dictionary, pass the source object as the constructor argument when declaring and defining the destination Dictionary.

Example:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpDictionary
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Dictionary<string, string> students = new Dictionary<string, string>();
  10. //Add some elements
  11. students.Add("ID01", "James");
  12. students.Add("ID02", "Roland");
  13. students.Add("ID03", "Mike");
  14. students.Add("ID04", "Martin");
  15. //Print students
  16. Console.WriteLine("students:");
  17. Print(students);
  18. //Copy
  19. Dictionary<string, string> students2 = new Dictionary<string, string>(students);
  20. Console.WriteLine("students2:");
  21. Print(students2);
  22. //Modifiy vlaue
  23. students2["ID03"] = "Mike 2";
  24. Console.WriteLine("students2 after modifying:");
  25. Print(students2);
  26. }
  27. static void Print(Dictionary<string, string> dictionary)
  28. {
  29. foreach (KeyValuePair<string, string> keyvaluepair in dictionary)
  30. {
  31. Console.WriteLine("[Key: {0}, Value: {1}]", keyvaluepair.Key, keyvaluepair.Value);
  32. }
  33. }
  34. }
  35. }

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.


See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# Variables