Wednesday, March 14, 2012

Dictionary in C#

Author : Prakash Pradeep Gopu


Dictionary in the c# used to represent a collection of keys and values pair of data.It allows you define the keys and values of any type.It belongs to the generic collection group in c# . The Dictionary type in the C# language provides very fast lookups with keys to get values.

Creating a Dictionary

The Dictionary class is a generic class and can store any data types. This class is defined in the System.Collections.Generic namespace.so If you want to create a dictionary you need to import the “System.Collections.Generic” Name space.
 using System.Collections.Generic;
For creating a dictionary object we will use the new key word.new keyword will allocate the memory. 
Syntax : Dictionary<TKey, TValue> objectname=new Dictionary<TKey, TValue>;
Where TKey -- The type of the keys in the dictionary.
            TValue-- The type of the values in the dictionary.

The following code will create the simple Dictionary and adding values to the Dictionary:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BloggerExamples
{
    class Dictionaryexample
    {
        static void Main(string[] args)
        {
            // Creating the Dictionary
            Dictionary<string, Int16> NameList = new Dictionary<string, Int16>();

            // Adding the dictionary Item Use Add() method
            NameList.Add("Prakash", 12);
            NameList.Add("Sandeep", 13);
            NameList.Add("Sathya", 14);
            NameList.Add("Sandya", 15);

            // Reading all data in the dictionary
            Console.WriteLine("Name List");
            foreach (KeyValuePair<string, Int16> Names in NameList)
            {

                Console.WriteLine("Key = {0}, Value = {1}", Names.Key, Names.Value);

            }
         

            //Look up values
            //Checking the key exist or not by using the ContainsKey()
            Console.WriteLine("Look up value for sandeep");
            if (NameList.ContainsKey("Sandeep"))
            {
                // if it exist then lookup the value of sandeep and returns the integer.
                int value = NameList["Sandeep"];
                Console.WriteLine(value);
            }

            Console.Read();

        }


    }
}


OutPut :


Interview Questions :

1) Who is faster hashtable or dictionary ? View Answer
2)  What is Difference between hash table and Dictionary? View Answer




No comments:

Post a Comment