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 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.
- class Student {
- public int StudentId { get; set; }
- public string StudentName { get; set; }
- public string Gender { get; set; }
- public double TotalMarks { get; set; }
- }
I have another class named “Program” that has the Main method that creates multiple objects of our Student class.
- class Program {
- static void Main(string[] args) {
- Student sOne = new Student() { StudentId = 201, StudentName = "Aiden Pearce", Gender = "Male", TotalMarks = 455.50 };
- Student sTwo = new Student() { StudentId = 202, StudentName = "Lara Croft", Gender = "Female", TotalMarks = 455.50 };
- Student sThree = new Student() { StudentId = 203, StudentName = "Black Widow", Gender = "Female", TotalMarks = 342 };
- Student sFour = new Student() { StudentId = 204, StudentName = "Sam Fisher", Gender = "Male", TotalMarks = 550.12 };
- Student sFive = new Student() { StudentId = 205, StudentName = "Max Payne", Gender = "Male", TotalMarks = 288.50 };
- }
- }
Now let's go ahead and create a new StudentDictionary Dictionary's object.
- 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.
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.
- Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>();
- StudentDictionary.Add(sOne.StudentId, sOne);
- StudentDictionary.Add(sTwo.StudentId, sTwo);
- StudentDictionary.Add(sThree.StudentId, sThree);
- StudentDictionary.Add(sFour.StudentId, sFour);
- 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.
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.
- Student s = StudentDictionary[202];
- Console.WriteLine("Student Name is {0}",string.Concat(s.StudentName));
The following is the current structure of the Main method.
- static void Main(string[] args) {
- Student sOne = new Student() { StudentId = 201, StudentName = "Aiden Pearce", Gender = "Male", TotalMarks = 455.50 };
- Student sTwo = new Student() { StudentId = 202, StudentName = "Lara Croft", Gender = "Female", TotalMarks = 455.50 };
- Student sThree = new Student() { StudentId = 203, StudentName = "Black Widow", Gender = "Female", TotalMarks = 342 };
- Student sFour = new Student() { StudentId = 204, StudentName = "Sam Fisher", Gender = "Male", TotalMarks = 550.12 };
- Student sFive = new Student() { StudentId = 205, StudentName = "Max Payne", Gender = "Male", TotalMarks = 288.50 };
-
-
- Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>();
-
- StudentDictionary.Add(sOne.StudentId, sOne);
- StudentDictionary.Add(sTwo.StudentId, sTwo);
- StudentDictionary.Add(sThree.StudentId, sThree);
- StudentDictionary.Add(sFour.StudentId, sFour);
- StudentDictionary.Add(sFive.StudentId, sFive);
-
- Student s = StudentDictionary[202];
- Console.WriteLine("Student Name is {0}",string.Concat(s.StudentName));
- }
Run the application.
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.
- foreach (KeyValuePair<int,Student> students in StudentDictionary) {
-
- }
To get the key from the KeyValuePair struct, we can say:
- foreach (KeyValuePair<int,Student> students in StudentDictionary) {
- Console.WriteLine(students.Key);
- }
The return type of the key property is an int that returns the StudentId back.
Run the application.
Now what is the value over here?
It is nothing but the Student object itself.
The return type of the value property is a Student object. That means we can store it in a Student object.
- foreach (KeyValuePair<int,Student> students in StudentDictionary) {
- 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.
- foreach (KeyValuePair<int,Student> students in StudentDictionary) {
- Student ss = students.Value;
- Console.WriteLine(ss.StudentName);
- }
Run the application.
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.
- StudentDictionary.Add(sOne.StudentId, sOne);
- StudentDictionary.Add(sTwo.StudentId, sTwo);
- StudentDictionary.Add(sThree.StudentId, sThree);
- StudentDictionary.Add(sFour.StudentId, sFour);
- StudentDictionary.Add(sFive.StudentId, sFive);
Now let's add another set of Student object sFive.
- 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.
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:
- if (StudentDictionary.ContainsKey(sFive.StudentId)) {
- Console.WriteLine("The key {0} already exists",string.Concat(sFive.StudentId));
- }
- else{
- StudentDictionary.Add(sFive.StudentId, sFive);
- }
Run the application.
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.
- Student s = StudentDictionary[220];
- Console.WriteLine("Student Name is {0}",string.Concat(s.StudentName));
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.
If the match is found, we want the student name with that id.
- Student outStudent = new Student();
- if (StudentDictionary.TryGetValue(203,out outStudent)) {
- Console.WriteLine(outStudent.StudentName);
- } else {
- Console.WriteLine("Invalid key");
- }
Run the application.
Pass an invalid key like 2345.
Count property
To know the total items present in a dictionary, use the Count Property.
- int TotalItems = StudentDictionary.Count;
- Console.WriteLine(TotalItems);
The return type of this property is integer.
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.
- int TotalItem = StudentDictionary.Count(x => x.Value.TotalMarks > 400);
- Console.WriteLine(TotalItem);
Run the application.
Remove method
To remove an item, use the Remove method.
Pass the key as a parameter in this method.
- StudentDictionary.Remove(sOne.StudentId);
- foreach (KeyValuePair<int, Student> students in StudentDictionary) {
- Student ss = students.Value;
- Console.WriteLine(ss.StudentName);
- }
Run the application.
Only four student names are displayed.
Clear method
This method removes all the items from a dictionary.
- StudentDictionary.Clear();
- foreach (KeyValuePair<int, Student> students in StudentDictionary) {
- Student ss = students.Value;
- Console.WriteLine(ss.StudentName);
- }
Run the application.
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.