Storing and retrieving simple values from a Dictionary in c#

Now that you know how to create an object of the Dictionary class lets learn how to store and retrieve values from a dictionary.

Adding values to a dictionary

When you add some data to a dictionary you will have to provide both key and value pair. For example if we decide to store the roll number and names of all students in a class using a dictionary then this is how our code will look like

class Program  {      static void Main(string[] args)      {          Dictionary<int, string> studentInfo = new Dictionary<int, string>();            // Add students to the dictionary          studentInfo.Add(1, "Movin");          studentInfo.Add(2, "Jasneet");          studentInfo.Add(3, "Silky");        }  }

See how we are adding information to the dictionary by providing both key and value. In this case our key is an integer and our value is a string.

Accessing values from a dictionary

To access the data from a dictionary you can use a foreach loop but for that you will have to learn a few other things. Therefore over here we will only teach you how to access data from a dictionary by giving the key and retrieving its value. Look at the code below

class Program  {      static void Main(string[] args)      {          Dictionary<int, string> studentInfo = new Dictionary<int, string>();            // Add students to the dictionary          studentInfo.Add(1, "Movin");          studentInfo.Add(20, "Jasneet");          studentInfo.Add(31, "Silky");            Console.WriteLine("Student with roll number 1 is : " + studentInfo[1]);          Console.WriteLine("Student with roll number 20 is : " + studentInfo[20]);          Console.WriteLine("Student with roll number 31 is : " + studentInfo[31]);      }  }

See how we are supplying the key to the dictionary and getting the value back. We are printing the value directly using the Console.WriteLine method because the value we are getting back is a string. If the value you get back is an object type then you will not be able to print its value directly by using the Console.WriteLine method.

Quick Links

E-Magazines

@

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..

Ok

Login to Open ESchool OR Create your account    Login   SignUp