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.
- Dictionary<int, string> students = new Dictionary<int, string>();
Add the values into students of Dictionary.
- students.Add(1, "Shamim");
- students.Add(2, "Seam");
- students.Add(3, "Mamun");
Read all the data.
- foreach (KeyValuePair<int, string> astudent in students)
- {
- Console.WriteLine("Key = {0}, Value = {1}",
- astudent.Key, astudent.Value);
- }
Output
Non-primitive data types
Now, we will create an Employee class. The class is given below.
- public class Employee
- {
- public int Id { set; get; }
- public string Name { get; set; }
- public string Desgination { get; set; }
- public int Salary { get; set; }
- }
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.
- Employee employee1 = new Employee() { Id = 111, Name = "Popy", Desgination = "Software", Salary = 35000 };
- Employee employee2 = new Employee() { Id = 112, Name = "Popy", Desgination = "Software", Salary = 35000 };
- Employee employee3 = new Employee() { Id = 113, Name = "Mitila", Desgination = "Sr.Software", Salary = 35000 };
Add the values into employees of Dictionary.
- employees.Add(employee1.Id,employee1);
- employees.Add(employee2.Id, employee2);
- employees.Add(employee3.Id, employee3);
Read all the data.
- foreach (KeyValuePair<int, Employee> aemployee in employees)
- {
- Console.WriteLine("Name = {0}, Desgination = {1}, Salary = {2}",
- aemployee.Value.Name, aemployee.Value.Desgination, aemployee.Value.Salary);
- }
Output
The count number of the items of dictionary is given below.
- int numberofRow = employees.Count;
Remove an item from dictionary.
- employees.Remove(employee3.Id);
Clear dictionary items
Hope, this will be helpful.