07
Use of Dictionary in C#
Filed Under (Uncategorized) by Ramin on 07-09-2009
“Dictionary”, the name proves the way of it works. In array we save data one after another and while accessing them we need to put the index and get the appropriate data. In dictionary data is saved with a key value. Dictionary accepts data with a key and while getting data from dictionary the key is provided and the data is fetched.
Example: Suppose 10 employees are there. However the employee will be selected and instantly his/her city is to be displayed. In dictionary we will set ID of the employee as key and the city of the employee as value like following:
Dictionary<int, string> dicEmp = new Dictionary<int, string>();
dicEmp.Add(1, “Kolkata”);
dicEmp.Add(2, “Mumbai”);
dicEmp.Add(4, “Bangalore”);
dicEmp.Add(5, “Delhi”);
In this way the values are saved into dictionary. Please mind before using dictionary “System.Collection.Generic” namespace should be added.
Now how to get data from dictionary?
Suppose the user selects employee whose id is 2 which is set into suppose variable empid.
label1.text = dicEmp[empid];
That is how dictionary is utilized.
