Dictionary in C#

Generic Dictionary in C# with Examples

In this article, I am going to discuss Generic Dictionary in C# with examples. Please read our previous article where we discussed Generic List Collection Class in detail. At the end of this article you will understand what exactly the Generic Dictionary is and when and how to use Dictionary in C# with examples.

What is Dictionary in C#?

The Dictionary in C# is a Collection class same as HashTable i.e. used to store the data in the form of Key Value Pairs, but here while creating the dictionary object you need to specify the type for the keys as well as the type for values also. The Syntax is given below:

Dictionary<TKey, TValue> di = new Dictionary<string, object>();

Example to Understand Dictionary Collection class:

Let us understand the Generic Dictionary Collection class with an example. First, create a collection class and then modify the Program class as shown below.

namespace DictionaryCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Dictionary represents a collection of keys and values
            Dictionary<string, object> di = new Dictionary<string, object>();

            //adds the specified key and value to the dictionary
            di.Add("Eno", 1001); 
            di.Add("Ename", "Pranaya");
            di.Add("Job", "Developer");
            di.Add("Salary", 7500);
            di.Add("Location", "Mumbai");
            
            //Loopig through each keys to get the values
            foreach (string key in di.Keys)
            {
                Console.WriteLine(key + " : " + di[key]);
            }
            Console.WriteLine();

            //removes the specified key with the value from the dictionary
            Console.WriteLine("After Removing the Job Key : ");
            di.Remove("Job"); 
            foreach (string key in di.Keys)
            {
                Console.WriteLine(key + " : " + di[key]);
            }
            Console.ReadKey();
        }
    }
}

OUTPUT:

Dictionary in C#

Points to Remember while working with Dictionary Generic Collection:
  1. A dictionary is a collection of (key, value) pairs.
  2. The Dictionary Generic Collection class is present in System.Collections.Generic namespace.
  3. When creating a dictionary, we need to specify the type for the key and as well as for the value.
  4. The fastest way to find a value in a dictionary is by using the keys.
  5. Keys in a dictionary must be unique.

Let’s use see an example of dictionary generic collection using the key as an integer and values as a complex type.

Note: The below example code is self-explained. Please go through the comment lines.

namespace DictionaryCollectionDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            //Create Employee object
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Gender = "Male",
                Salary = 20000
            };
            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Priyanka",
                Gender = "Female",
                Salary = 30000
            };
            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Anurag",
                Gender = "Male",
                Salary = 40000
            };

            // Create a Dictionary collection where 
            // Employee ID is the key and the key Type is int
            // Employee object is the value and the value Type is Employee
            Dictionary<int, Employee> dictionaryEmployees = new Dictionary<int, Employee>();

            // Add Employee objects to the dictionary collection
            // Employee ID is the key and the employee object is the value
            dictionaryEmployees.Add(emp1.ID, emp1);
            dictionaryEmployees.Add(emp2.ID, emp2);
            dictionaryEmployees.Add(emp3.ID, emp3);

            // Retrieve the value (i.e. Employee object) from the dictionary
            // using the key (i.e. Employee ID). 
            // The fastest way to get a value from the dictionary is by using its key
            Employee employee101 = dictionaryEmployees[101];
            Console.WriteLine("Employee 101 in employee dictionary");
            Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                            employee101.ID, employee101.Name, employee101.Gender, employee101.Salary);
            Console.WriteLine();

            // It is also possible to loop thru each key/value pair in a dictionary
            Console.WriteLine("All Employees keys and values in employee dictionary");
            foreach (KeyValuePair<int, Employee> employeeKeyValuePair in dictionaryEmployees)
            {
                Console.WriteLine("Key = " + employeeKeyValuePair.Key);
                Employee emp = employeeKeyValuePair.Value;
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp.ID, emp.Name, emp.Gender, emp.Salary);
            }
            Console.WriteLine();

            // We can also use implicitly typed variable var to loop thru 
            // each key/value pair in a dictionary. 
            // But try to avoid using var, as this makes our code less readable
            Console.WriteLine("All Employees keys and values in employee dictionary");
            foreach (var employeeKeyValuePair in dictionaryEmployees)
            {
                Console.WriteLine("Key = " + employeeKeyValuePair.Key);
                Employee emp = employeeKeyValuePair.Value;
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp.ID, emp.Name, emp.Gender, emp.Salary);
            }
            Console.WriteLine();

            // To get all the keys in the dictionary we have to use the keys properties
            // of dictionaryCustomers object as shown below
            Console.WriteLine("All Keys in Employee Dictionary");
            foreach (int key in dictionaryEmployees.Keys)
            {
                Console.WriteLine(key + " ");
            }
            Console.WriteLine();

            // First get the keys, then get the values using the keys
            Console.WriteLine("All Keys and values in Employee Dictionary");
            foreach (int key in dictionaryEmployees.Keys)
            {
                Console.WriteLine(key + " ");
                Employee emp = dictionaryEmployees[key];
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp.ID, emp.Name, emp.Gender, emp.Salary);
            }
            Console.WriteLine();
            
            //To get all the values in the dictionary use Values property
            Console.WriteLine("All employees objects in Employee Dictionary");
            foreach (Employee emp in dictionaryEmployees.Values)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp.ID, emp.Name, emp.Gender, emp.Salary);
            }

            // If we try to add a key that already exists in the dictionary we will get an exception - 
            // An item with the same key has already been added. So, check if the key already exists
            if (!dictionaryEmployees.ContainsKey(101))
            {
                dictionaryEmployees.Add(101, emp1);
            }
            Console.WriteLine();

            // When accessing a dictionary value by key, make sure the dictionary contains the key, 
            // otherwise we will get KeyNotFound exception.
            if (dictionaryEmployees.ContainsKey(110))
            {
                Employee emp = dictionaryEmployees[110];
            }
            else
            {
                Console.WriteLine("Key does not exist in the dictionary");
            }

            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
OUTPUT:

Dictionary Generic Collection Class in C#

Collection Initializers in C#:

This is a new feature added to C# 3.0 which allows initializing a collection directly at the time of declaration like an array.

A Dictionary<TKey,TValue> contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value. To initialize a Dictionary<TKey,TValue>, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces.

Example:
namespace DictionaryCollectionDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            // Collection initializer
            // Initializing the collection directly at the time of declaration
            Dictionary<int, Employee> dictionaryEmployees = new Dictionary<int, Employee>()
            {
                { 101, new Employee {ID=101, Name="Pranaya", Gender="Male", Salary = 20000}},
                { 102, new Employee {ID=101, Name="Priyanka", Gender="Female", Salary = 30000}},
                { 103, new Employee {ID=101, Name="Anurag", Gender="Male", Salary = 40000}}
            };
            
            //To get all the values in the dictionary use Values property
            Console.WriteLine("All employees objects in Employee Dictionary");
            foreach (Employee emp in dictionaryEmployees.Values)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp.ID, emp.Name, emp.Gender, emp.Salary);
            }
            
            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
OUTPUT:

:Dictionary Generic Collection Class in C#

Dictionary Class important Methods:

The Generic Dictionary Collection class stores the data in the form of key-value pairs. Now, let us see the following Dictionary class methods in detail.

TryGetValue():

This method takes two parameters, one is the key and the other one is the value. The value type parameter is of type out parameter. If the key exists in the dictionary then it will return true and the value with that associated key is stored on the output variable.

Note: If you are not sure if a key is present or not in the dictionary, then you can use the TryGetValue() method to get the value from a dictionary because if you are not using TryGetValue then at that case you will get KeyNotFoundException

Count(): 

The Count() function is used to find the total number of items in a dictionary.

Remove(): 

If you want to remove an item from the dictionary collection, then you need to use the Remove() method.

Clear(): 

The Clear() method is used to remove all the items from the dictionary.

Note: We will see how to use LINQ extension methods with Dictionary and different ways to convert an array into a dictionary.

Example to understand the above methods.

The code is self-explained. Please go through the comments.

namespace DictionaryCollectionDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            //Create Employee object
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Gender = "Male",
                Salary = 20000
            };
            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Priyanka",
                Gender = "Female",
                Salary = 30000
            };
            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Anurag",
                Gender = "Male",
                Salary = 40000
            };

            // Create a Dictionary collection where 
            // Employee ID is the key and the key Type is int
            // Employee object is the value and the value Type is Employee
            Dictionary<int, Employee> dictionaryEmployees = new Dictionary<int, Employee>();

            // Add Employee objects to the dictionary collection
            // Employee ID is the key and the employee object is the value
            dictionaryEmployees.Add(emp1.ID, emp1);
            dictionaryEmployees.Add(emp2.ID, emp2);
            dictionaryEmployees.Add(emp3.ID, emp3);

            // If you are not sure if a key is present or not in the dictionary, 
            // then you can use the TryGetValue() method to get the value from a dictionary because 
            // if you are not using TryGetValue then at that case you will get KeyNotFoundException
            Employee emp777;
            if (dictionaryEmployees.TryGetValue(777, out emp777))
            {
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp777.ID, emp777.Name, emp777.Gender, emp777.Salary);
            }
            else
            {
                Console.WriteLine("Employee with Key = 777 is not found in the dictionary");
                Console.WriteLine();
            }

            // To find the total number of items in a dictionary use Count() method
            Console.WriteLine("Total items in Employee Dictionary = {0}", dictionaryEmployees.Count());
            // Or You can use the Count Property
            // Console.WriteLine("Total items in Employee Dictionary = {0}", dictionaryEmployees.Count);
            Console.WriteLine();

            // LINQ extension methods can also be used with the Dictionary. 
            // For example, to find the total employees whose Gender is Male.
            Console.WriteLine("Total Employees in the dictionary where Gender is Male = {0}",
                              dictionaryEmployees.Count(kvp => kvp.Value.Gender == "Male"));
            Console.WriteLine();

            // To remove an item from the dictionary, use Remove() method
            dictionaryEmployees.Remove(101);

            // To remove all items from the dictionary, use Clear() method
            dictionaryEmployees.Clear();

            //Now our dictionary is empty

            // Create an array of employees with size 3
            // Store the 3 employees into the array
            Employee[] arrayEmployees = new Employee[3];
            arrayEmployees[0] = emp1;
            arrayEmployees[1] = emp2;
            arrayEmployees[2] = emp3;

            // Convert Employee array to a dictionary using ToDictionary() method.
            // In this example, key is Employee ID and the value is the employee object itself
            Dictionary<int, Employee> dict = arrayEmployees.ToDictionary(employee => employee.ID, employee => employee);
            // OR        
            // Dictionary<int, Employee> dict = arrayEmployees.ToDictionary(employee => employee.ID);
            //OR use a foreach loop
            //Dictionary< int, Employee> dict = new Dictionary<int, Employee>();
            //foreach (Employee emp in arrayEmployees)
            //{
            //    dict.Add(emp.ID, emp);
            //}

            // Loop thru the dictionary and print the key/value pairs
            foreach (KeyValuePair<int, Employee> kvp in dict)
            {
                Console.WriteLine("Key = {0}", kvp.Key);
                Employee emp = kvp.Value;
                Console.WriteLine("ID = {0}, Name = {1}, Gender ={2}, Salary = {3}",
                               emp.ID, emp.Name, emp.Gender, emp.Salary);
            }
            
            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
OUTPUT:

Generic Dictionary Class important methods in C#  

In the next article, I am going to discuss some import the conversion between Array List and Dictionary in C#. Here, in this article, I try to explain Generic Dictionary in C# with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *