Dictionary in C#


Dictionary is used to represent a collection of key and Value pair of data. It is a generic class and it can store any data type. It came with .net F/W 2.0.

Dictionary contains key and value together as shown in given example below


 protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, int> Emps = new Dictionary<string, int>();
        Emps.Add("Ram", 1);
        Emps.Add("Mohan", 2);
        Emps.Add("Hari", 3);
        foreach (var name in Emps)
        {
            lblmsg.Text += name.Key + " " + name.Value  +"<br>";
        }     
    }

Then output will come like this

Ram 1
Mohan 2
Hari 3

ContainKey and ContainValue Method

It has containkey and ContainValue method. Using ContainKey we can find the specific key in dictionary and using ContainValue we can get the specific value. It returns the Boolean value.


 if(Emps.ContainsKey("Hari"))
        {
            int value = Emps["Hari"];
            lblmsg.Text = value.ToString();
        }


It has also add,remove and Clear method.

Advantages

1. Dictionary type provides fast lookups with keys to get values.
2. It stores any datatype
3. It provide good performance as compare to HashTable

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.