Dictionary in C#

The Dictionary class is a collection of key/value pairs and is in the System.Collections.Generic namespace.

When creating a dictionary, we need to specify the type for the key and the value.

TKey

TKey is the type of the key we pass in and the key must be unqiue.

TValue is the type of value we pass in.

Let's look at an example.

In Visual Studio, I have created a console application “DictionaryIncsharp” in which there is a class “Student” with four auto-implemented properties.

  1. class Student {  
  2.     public int StudentId { getset; }  
  3.     public string StudentName { getset; }  
  4.     public string Gender { getset; }  
  5.     public double TotalMarks { getset; }  

I have another class named “Program” that has the Main method that creates multiple objects of our Student class.

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         Student sOne = new Student() { StudentId = 201, StudentName = "Aiden Pearce", Gender = "Male", TotalMarks = 455.50 };  
  4.         Student sTwo = new Student() { StudentId = 202, StudentName = "Lara Croft", Gender = "Female", TotalMarks = 455.50 };  
  5.         Student sThree = new Student() { StudentId = 203, StudentName = "Black Widow", Gender = "Female", TotalMarks = 342 };  
  6.         Student sFour = new Student() { StudentId = 204, StudentName = "Sam Fisher", Gender = "Male", TotalMarks = 550.12 };  
  7.         Student sFive = new Student() { StudentId = 205, StudentName = "Max Payne", Gender = "Male", TotalMarks = 288.50 };  
  8.     }  

Now let's go ahead and create a new StudentDictionary Dictionary's object.

  1. Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>(); 

int is the type of key and value will be of type student.

To add an item to a dictionary, the Add method can be used.

Add method

The first parameter expects a key of type int because when creating a StudentDictionary we specified that the key type is an int.

The second parameter expects a value of type student object because when creating a StudentDictionary we specified the value type as Student.

We will pass the key StudentId.

We will pass the value student object.

  1. Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>();  
  2. StudentDictionary.Add(sOne.StudentId, sOne);  
  3. StudentDictionary.Add(sTwo.StudentId, sTwo);  
  4. StudentDictionary.Add(sThree.StudentId, sThree);  
  5. StudentDictionary.Add(sFour.StudentId, sFour);  
  6. StudentDictionary.Add(sFive.StudentId, sFive); 

At this point we have created a StudentDictionary and added student objects into this dictionary.

Now the next thing is to find the values from this dictionary and the best way to find the values is by using a key.

key

To find the records of one student, we can pass the key as an index value in the StudentDictionary that will return a Student object back that means we can store the records in a new Student object.

  1. Student s = StudentDictionary[202];  
  2. Console.WriteLine("Student Name is {0}",string.Concat(s.StudentName)); 

The following is the current structure of the Main method.

  1. static void Main(string[] args) {  
  2.     Student sOne = new Student() { StudentId = 201, StudentName = "Aiden Pearce", Gender = "Male", TotalMarks = 455.50 };  
  3.     Student sTwo = new Student() { StudentId = 202, StudentName = "Lara Croft", Gender = "Female", TotalMarks = 455.50 };  
  4.     Student sThree = new Student() { StudentId = 203, StudentName = "Black Widow", Gender = "Female", TotalMarks = 342 };  
  5.     Student sFour = new Student() { StudentId = 204, StudentName = "Sam Fisher", Gender = "Male", TotalMarks = 550.12 };  
  6.     Student sFive = new Student() { StudentId = 205, StudentName = "Max Payne", Gender = "Male", TotalMarks = 288.50 };  
  7.   
  8.       
  9.     Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>();  
  10.   
  11.     StudentDictionary.Add(sOne.StudentId, sOne);  
  12.     StudentDictionary.Add(sTwo.StudentId, sTwo);  
  13.     StudentDictionary.Add(sThree.StudentId, sThree);  
  14.     StudentDictionary.Add(sFour.StudentId, sFour);  
  15.     StudentDictionary.Add(sFive.StudentId, sFive);  
  16.   
  17.     Student s = StudentDictionary[202];  
  18.     Console.WriteLine("Student Name is {0}",string.Concat(s.StudentName));  

Run the application.

Console

We got the name of the student whose id is 202.

Now let's say we want the name of all the students from the StudentDictionary object. To get all the student's names we need to loop through each item of the StudentDictionary and for that we can use foreach loop.

As we know a Dictionary is a collection of key/value pairs. That means it will return a key/value pair.

So, when we loop through a StudentDictionary, it will return a KeyValuePair back.

  1. foreach (KeyValuePair<int,Student> students in StudentDictionary) {  
  2.   

To get the key from the KeyValuePair struct, we can say:

  1. foreach (KeyValuePair<int,Student> students in StudentDictionary) {  
  2.    Console.WriteLine(students.Key);  

The return type of the key property is an int that returns the StudentId back.

Run the application.

StudentId

Now what is the value over here?

It is nothing but the Student object itself.

  1. students.Value; 

The return type of the value property is a Student object. That means we can store it in a Student object.

  1. foreach (KeyValuePair<int,Student> students in StudentDictionary) {  
  2.    Student ss = students.Value;  

Now from this student's "ss" object we can invoke all the properties of the student class but we want only the StudentName property.

  1. foreach (KeyValuePair<int,Student> students in StudentDictionary) {  
  2.    Student ss = students.Value;  
  3.    Console.WriteLine(ss.StudentName);  

Run the application.

StudentName

The key must be unique. So, what will happen if we pass a duplicate record?

Currently in the StudentDictionary object we have added five sets of student objects.

  1. StudentDictionary.Add(sOne.StudentId, sOne);  
  2. StudentDictionary.Add(sTwo.StudentId, sTwo);  
  3. StudentDictionary.Add(sThree.StudentId, sThree);  
  4. StudentDictionary.Add(sFour.StudentId, sFour);  
  5. StudentDictionary.Add(sFive.StudentId, sFive); 

Now let's add another set of Student object sFive.

  1. StudentDictionary.Add(sFive.StudentId, sFive); 

Our dictionary object already contains the key of a sFive object. So, when we run the application we will get an exception.

dictionary

So, it is always a good practice to check if the dictionary object already contains a specific key and for that we can use ContainsKey that is a Boolean method.

Pass the key as a parameter argument as in the following:

  1. if (StudentDictionary.ContainsKey(sFive.StudentId)) {  
  2.    Console.WriteLine("The key {0} already exists",string.Concat(sFive.StudentId));  
  3. }  
  4. else{  
  5.    StudentDictionary.Add(sFive.StudentId, sFive);  

Run the application.

StudentDictionary

Not just when adding, we can also get an exception when we are retrieving.

Let's say we don't know if the key 220 is present or not and if we try to retrieve the records using that key, we will get an exception.

  1. Student s = StudentDictionary[220];  
  2. Console.WriteLine("Student Name is {0}",string.Concat(s.StudentName)); 

exception

Here too we can use the ContainsKey method.

Let's look at some more methods and a property of the Dictionary class.

TryGetValue method

So, when do we use this method?

If you are not sure whether a Dictionary object contains a specific key then use TryGetValue.

It is a Boolean method that expects two parameters. The first parameter is the key that is an input parameter and the second one is the value that is an output parameter that will receive the value if the specific key is associated with it.

TryGetValue

If the match is found, we want the student name with that id.

  1. Student outStudent = new Student();  
  2.    if (StudentDictionary.TryGetValue(203,out outStudent)) {  
  3.       Console.WriteLine(outStudent.StudentName);  
  4.    } else {  
  5.    Console.WriteLine("Invalid key");  

Run the application.

Run

Pass an invalid key like 2345.

Pass an invalid key

Count property

To know the total items present in a dictionary, use the Count Property.

  1. int TotalItems = StudentDictionary.Count;  
  2. Console.WriteLine(TotalItems); 

The return type of this property is integer.

Run the application.

Run the application

Count method

There is another way to count the total items present in a dictionary based on some condition.

The Count method is an extension method present in the System.Linq namespace.

Let's say we want to count only the items whose Marks is greater than 400.

  1. int TotalItem = StudentDictionary.Count(x => x.Value.TotalMarks > 400);  
  2. Console.WriteLine(TotalItem); 

Run the application.

Count method

Remove method

To remove an item, use the Remove method.

Pass the key as a parameter in this method.

  1. StudentDictionary.Remove(sOne.StudentId);  
  2.    foreach (KeyValuePair<int, Student> students in StudentDictionary) {  
  3.    Student ss = students.Value;  
  4.    Console.WriteLine(ss.StudentName);  

Run the application.

output

Only four student names are displayed.

Clear method

This method removes all the items from a dictionary.

  1. StudentDictionary.Clear();  
  2.    foreach (KeyValuePair<int, Student> students in StudentDictionary) {  
  3.    Student ss = students.Value;  
  4.    Console.WriteLine(ss.StudentName);  

Run the application.

Run program

In this article we have learned about the Dictionary class that is a collection of key/value pairs. It is used for fast lookups and the key must be unique.

The next article explains the List class.

Until then keep learning.

Up Next
    Ebook Download
    View all
    Learn
    View all