Dictionary

C# Dictionary


  • The Dictionary<TKey, TValue> class is a generic collection class in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.
  • There is a non-generic collection called a Hashtable, which does the same thing, except that it operates on type object. However, you want to avoid the non-generic collections and use their generic counterparts instead
  • Dictionary cannot include duplicate or null keys, where as values can be duplicated or set as null. Keys must be unique otherwise it will throw a runtime exception.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.


Properties

 Property

 Description

 Count             Gets the total number of elements exists in the Dictionary<TKey,TValue>              .
 IsReadOnly Returns a boolean indicating whether the Dictionary<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.
 Keys Returns collection of keys of Dictionary<TKey,TValue>.
 Values Returns collection of values in Dictionary<TKey,TValue>.

Methods


 Method     Description
 Add                Add key-value pairs in Dictionary<TKey, TValue> collection.                                                                  
 Remove     Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.
 ContainsKey  Checks whether the specified key exists in Dictionary<TKey, TValue>.
 ContainsValue Checks whether the specified key exists in Dictionary<TKey, TValue>.
 Clear Removes all the elements from Dictionary<TKey, TValue>.
 TryGetValue Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 public static void Main(String[] args)
   {
           
            Dictionary<int, string> _dictionary =  new Dictionary<int, string>();

            // Adding key/value pairs  
            _dictionary.Add(1, "Hello");
            _dictionary.Add(2, "This is");
            _dictionary.Add(3, "Blog for C#");

            _dictionary.Remove(1); //Remove value which key is 1

            Console.WriteLine("Is Key Exist?: {0}",_dictionary.ContainsKey(2));//Return True
            Console.WriteLine("Is Value Exist?: {0}", _dictionary.ContainsValue("This is"));//Return True
            foreach (KeyValuePair<int, string> ele1 in _dictionary)
            {
                Console.WriteLine("{0} and {1}",
                          ele1.Key, ele1.Value);
            }
            Console.ReadLine();

           
    }

No comments:

Post a Comment

Please let me know if you have any feedback or doubts.

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...