Storing and retrieving objects from a Dictionary in C#

Now that you know how to store simple values in a dictionary and how to retrieve them by supplying the key to the dictionary, in this tutorial you will learn how to store and retrieve objects from a dictionary

Storing objects in a dictionary

In the previous tutorial we stored only the roll number (integer) and name (string) of a student. In this tutorial we will store the full information about a student with his / her roll number as our key. This will help us in making sure that the information for each roll number is stored only once. Look at the code below

class Student  {      public int RollNo;      public string Name;      public String EmailId;  }    class Program  {      static void Main(string[] args)      {          Dictionary<int, Student> studentInfo = new Dictionary<int, Student>();            // Create new student object          Student student = new Student();          student.RollNo = 1;          student.Name = "Movin";          student.EmailId = "";            // Add this student object to the dictionary          studentInfo.Add(1, student);            // Create a second student object          student = new Student();          student.RollNo = 20;          student.Name = "Jasneet";          student.EmailId = "";            // Add this student object to the dictionary          studentInfo.Add(20, student);                 }  }

See how we are creating the objects of the student class and storing them in the dictionary using their roll numbers as the key. This way we are making sure that the information for roll number 1 only gets stored once in the dictionary.

Reading objects back from the dictionary

In our current example when we will supply a key to the dictionary it will give us back an object and not a simple value. So we will have to store the address of that object in some pointer and then access the properties of that object. Look at the code below

// Read information of roll number 20 from the dictionary    Student s1 = studentInfo[20];    Console.WriteLine("Name : " + s1.Name);  Console.WriteLine("Roll number : " + s1.RollNo);  Console.WriteLine("Email Id : " + s1.EmailId);

See how we are supplying the key to the dictionary and getting back an object. In this case our Student class pointer s1 will be pointing to the object we get back from the dictionary.

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