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
- Key in a dictionary cannot be null; however, a value can be.
- Key in the dictionary must be unique.
- 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>.
-
-
- Dictionary<int, string> empList =
- new Dictionary<int, string>();
-
-
-
- empList.Add(1, "X");
- empList.Add(2, "Y");
- empList.Add(3, "Z");
-
- foreach (KeyValuePair<int, string> emp in empList)
- {
- Console.WriteLine($"Employee Code - {emp.Key}, Employee Name - {emp.Value}");
- }
-
-
-
-
-
- Dictionary<string, string> empList2 =
- new Dictionary<string, string>(){
- {"IT", "Rahul"},
- {"Dev", "Raj"},
- {"HR", "Ayesha"} };
-
- foreach (KeyValuePair<string, string> emp in empList2)
- {
- Console.WriteLine($" Department - {emp.Key}, Employee Name - {emp.Value}");
- }
-
- #region Check Element/Value is Present
-
-
-
- if (empList.ContainsKey(3) == true)
- {
- Console.WriteLine("Key is found...!!");
- }
-
- else
- {
- Console.WriteLine("Key is not found...!!");
- }
-
-
-
- if (empList.ContainsValue("Z") == true)
- {
- Console.WriteLine("Value is found...!!");
- }
-
- else
- {
- Console.WriteLine("Value is not found...!!");
- }
-
- #endregion
-
- #region Remove Elements
-
-
- empList.Remove(2);
-
-
- foreach (KeyValuePair<int, string> emp in empList)
- {
- Console.WriteLine($"Employee Code - {emp.Key}, Employee Name - {emp.Value}");
- }
- Console.WriteLine();
-
-
-
- empList.Clear();
-
- Console.WriteLine($"Total key/value pairs present in empList:{empList.Count}");
-
- #endregion