Dictionary is a collection class in c# like Arraylist and list.The difference between list and dictionary is that in the case of list the items are accessed using integer index while in the case of dictionary items are accessed usingĀ a key which need not be an integer.
In .NET Dicionary is a generic class which has two type parameters TKey and TValue.It is part of the namespace System.Collections.Generic which contains generic collections such as lists.Unlike list in which you add just add the element ,in the case of dictionary you add a key value pair.When you add a key value pair,the key becomes associated with a value.You can use the key to access the value in the dictionary.Important point to understand is that though you can add two duplicate values in a dictionary ,you can not add duplicate key in the dictionary.
When you are iterating the elements of the dictionary then you will get back two items key and value.These key value pairs are defined in the KeyValuePair<TKey, TValue> class.It has two properties Key and Value.To fetch a key fof an item you use Key property while to fetch the value you use the Value property.
Creating a dictionary object
We can define the type of key and value we want to store in dictionary.In the following example we are storing both key and value as strings.
Dictionary<string, string> names = new Dictionary<string,string>();
We are defining a dictionary object which will contain the list of employees which are accessed using the employee id.
Adding an item to dictionary
We can add items to dictionary in two ways
using the Add() method of the dictionary object
names.Add("001", "John");
Directly assigning the value by using the key
We can directly assign a value to a given key in dictionary by using the key as accessor:
names["001"] = "John";
Looping dictionary items
We loop the contents of the dictionary by using the KeyValuePair objects in the dictionary:
foreach (KeyValuePair<string, string> item in names) { string name = element.Key; string empId = element.Value; Console.WriteLine("Name: {0}, Employee Id: {1}", name, empId); }
You can add any custom type as value.For example we can use a class as value.
If we define a student class as:
class Student { public string Name{ get;set;} public string Grade { get; set; } public string Marks { get; set; } }
then we can use define dictionary for this class as:
Student studentObj = new Student { Name = "Steve" }; Dictionary<string, Student> students1 = new Dictionary<string, Student>(); students1.Add("Steve", studentObj);
Leave a Reply