Dictionary In C#

Introduction

Dictionary class represents a collection of key values pair of the data. This class is a generic type, so this class can store any type of data. It can be primitive data types or non-primitive data types. First of all, we will discuss about primitive data types, followed by discussing about non-primitive data types.

Act

We can Add, Remove, Clear other collection methods. The key is used for get the value from a Dictionary.

Primitive data types

The code snippet given below creates a Dictionary named “students”, where the keys are integer and the value is a string.

  1. Dictionary<int, string> students = new Dictionary<int, string>();  

Add the values into students of Dictionary.

  1. students.Add(1, "Shamim");  
  2. students.Add(2, "Seam");  
  3. students.Add(3, "Mamun");  
Read all the data.  
  1. foreach (KeyValuePair<int, string> astudent in students)  
  2.       {  
  3.          Console.WriteLine("Key = {0}, Value = {1}",  
  4.          astudent.Key, astudent.Value);  
  5.       }  

Output

Output

Non-primitive data types

Now, we will create an Employee class. The class is given below.

  1. public class Employee  
  2.    {  
  3.        public int Id { set; get; }  
  4.        public string Name { get; set; }  
  5.        public string Desgination { get; set; }  
  6.        public int Salary { get; set; }  
  7.    }  

The code snippet given below creates a dictionary named employees, where the keys are integer and the value is an Employee type. Employee type is a custom create type.

Dictionary<int, Employee> employees = new Dictionary<int, Employee>(); Value assigns employee’s object. 

  1. Employee employee1 = new Employee() { Id = 111, Name = "Popy", Desgination = "Software", Salary = 35000 };  
  2.             Employee employee2 = new Employee() { Id = 112, Name = "Popy", Desgination = "Software", Salary = 35000 };  
  3.             Employee employee3 = new Employee() { Id = 113, Name = "Mitila", Desgination = "Sr.Software", Salary = 35000 };   

Add the values into employees of Dictionary. 

  1. employees.Add(employee1.Id,employee1);  
  2. employees.Add(employee2.Id, employee2);  
  3. employees.Add(employee3.Id, employee3);   

Read all the data. 

  1. foreach (KeyValuePair<int, Employee> aemployee in employees)  
  2.            {  
  3.                Console.WriteLine("Name = {0}, Desgination = {1}, Salary = {2}",  
  4.                aemployee.Value.Name, aemployee.Value.Desgination, aemployee.Value.Salary);  
  5.            }   

Output

Output

The count number of the items of dictionary is given below.

  1. int numberofRow = employees.Count;  

Remove an item from dictionary.

  1. employees.Remove(employee3.Id);  

Clear dictionary items

  1. employees.Clear();  

Hope, this will be helpful.