Dictionary is a generic collection used to store key/value pairs. Dictionary's work is very similar to the non-generic hashtable. Dictionary is defined under System.Collection.Generic namespace. The dictionary's size increases as needed. The Dictionary class uses interface, IReadOnlyCollection < KeyValuePair < TKey, TValue > Interface, IReadOnlyDictionary < TKey, TValue > Interface, and IDictionary Interface.

Key Points about Dictionary

  1. Key in a dictionary cannot be null; however, a value can be.
  2. Key in the dictionary must be unique.
  3. Dictionary is strongly typed, this means the dictionary accepts key/value of only the same types are defined.
Please refer to the below code which shows all the operations we can perform on Dictionary<TKey,TValue>.
  1. // Creating a dictionary
  2. // using Dictionary<TKey,TValue> class
  3. Dictionary<int, string> empList =
  4. new Dictionary<int, string>();
  5. // Add() method - For Adding key/value pairs in the Dictionary
  6. // Employee Code and Name
  7. empList.Add(1, "X");
  8. empList.Add(2, "Y");
  9. empList.Add(3, "Z");
  10. foreach (KeyValuePair<int, string> emp in empList)
  11. {
  12. Console.WriteLine($"Employee Code - {emp.Key}, Employee Name - {emp.Value}");
  13. }
  14. // Creating another dictionary
  15. // using Dictionary<TKey,TValue> class
  16. // adding key/value pairs without
  17. // using Add method - Department/EmpName
  18. Dictionary<string, string> empList2 =
  19. new Dictionary<string, string>(){
  20. {"IT", "Rahul"},
  21. {"Dev", "Raj"},
  22. {"HR", "Ayesha"} };
  23. foreach (KeyValuePair<string, string> emp in empList2)
  24. {
  25. Console.WriteLine($" Department - {emp.Key}, Employee Name - {emp.Value}");
  26. }
  27. #region Check Element/Value is Present
  28. // Using ContainsKey() method to check
  29. // the specified key is present or not
  30. if (empList.ContainsKey(3) == true)
  31. {
  32. Console.WriteLine("Key is found...!!");
  33. }
  34. else
  35. {
  36. Console.WriteLine("Key is not found...!!");
  37. }
  38. // Using ContainsValue() method to check
  39. // the specified value is present or not
  40. if (empList.ContainsValue("Z") == true)
  41. {
  42. Console.WriteLine("Value is found...!!");
  43. }
  44. else
  45. {
  46. Console.WriteLine("Value is not found...!!");
  47. }
  48. #endregion
  49. #region Remove Elements
  50. // Using Remove() method
  51. empList.Remove(2);
  52. // After Remove() method
  53. foreach (KeyValuePair<int, string> emp in empList)
  54. {
  55. Console.WriteLine($"Employee Code - {emp.Key}, Employee Name - {emp.Value}");
  56. }
  57. Console.WriteLine();
  58. // Using Clear() method
  59. empList.Clear();
  60. Console.WriteLine($"Total key/value pairs present in empList:{empList.Count}");
  61. #endregion