Dictionary Generic Collection in C#

Dictionary Generic Collection in C#

The Dictionary Generic Collection class is same as HashTable that we have discussed under collection but here while creating the object we need to specify the type for the keys as well as the type for values also.

Syntax:

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

Example:

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 Generic Collection Class 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:

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#

In the next article, I will discuss some import methods of Dictionary class.

SUMMARY:

In this article, I try to explain Dictionary Generic Collection Class 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 *