Working with the Dictionary<Key,Value> class

Another very important generic collection class which you will need to use very frequently when writing your software applications is the Dictionary<Key,Value> class. As you can understand from the signatures of this class that it takes two generic parameters. The first parameter is for the type of key the dictionary will have and the second parameter is for the type of value you want to store.

When should you use a dictionary?

There are many situations in programming when you will find the need to create a list of objects such that each object should be accessible via a unique key. Like for example you have a primary key in your database tables. This primary key helps you make sure that each record in the table is identifiable uniquely using its key. Dictionary is also based on the same concept. The key in the dictionary acts as a primary key for the object which you store as the value of that key.

A very simple example

Suppose you have to store the name and roll number of each student in a class. The rule is that no two students can have the same roll number but they can have the same name. This is a perfect case to use the Dictionary collection. In this case we will use the roll number as our key and the name of the students as our value.

Let’s suppose that the roll number of each student will be some integer value. The name is obviously a string value. Therefore we will be creating our Dictionary in the following manner

Dictionary<int, string> studentInfo = new Dictionary<int, string>();

Here we are telling the dictionary that our key will be of the type integer and the value we will store will be of the type string. Suppose you want to create a dictionary to store the information of all students in a class and this time you don’t just want to store their names but you want to store an object with complete student information. You also want that the information for one student should only be stored once. Therefore you want to use the dictionary class where the roll number will be our key and the Student object will be our value. This is how we will create our dictionary in this case

Dictionary<int, Student> studentInfo = new Dictionary<int, Student>();

In this case our key will be of the type integer but we will be storing a student object as our value.

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp