Advertisement



< Prev



C# Dictionary<TKey, TValue> Class



The generic Dictionary<TKey, TValue> collection class stores a collection of key-value pairs, where key and value are objects.

The Dictionary<TKey, TValue> uses a mechanism of hashing to store each key-value pair and to perform the association between each key-value pair. In hashing, a unique hash code of each key is computed internally and this value of hash code is used as an index at which its associated value is stored in the Dictionary<TKey, TValue>.

Dictionary<TKey, TValue> collection class is defined in the System.Collections.Generics namespace and it implements IDictionary, IDictionary<TKey, TValue>, ICollection, IEnumerable<KeyValuePair<TKey, TValue>> and many other interfaces.






Some important features of Dictionary<TKey, TValue>


  • The Dictionary<Key,TValue> class is implemented as a hash table, therefore, retrieving a value by using its key is very fast.





  • Constructors of Dictionary<TKey, TValue>


    Constructor Description
    Dictionary<T>()
    This constructor creates an empty instance of the Dictionary<TKey, TValue> class by using the default initial capacity, hash code provider, and comparer.

    The capacity of a Dictionary<TKey, TValue> is the number of elements it can hold, as the new elements are added to the Dictionary<TKey, TValue>, its capacity is automatically increased.

    Dictionary<T>(int capacity)
    This constructor initializes created a Dictionary<TKey, TValue> that is empty and has the specified initial capacity.

    Dictionary<T>(IDictionary<TKey, TValue>)
    This constructor creates a Dictionary<T> initialized with the elements of an IDictionary<TKey, TValue> collection.






    Properties of Dictionary<TKey, TValue>:


    Properties Description
    Capacity
    This property is used to get or set the total number of elements a Dictionary<TKey, TValue> can hold.

    Count
    This property gives total number of elements in a Dictionary<TKey, TValue>.

    IsFixedSize
    This property determines whether a Dictionary<TKey, TValue> has a fixed size or not.

    IsReadOnly
    This property determines whether a Dictionary<TKey, TValue> is read-only or not.

    IsSynchronzied
    This property determines whether a Dictionary<TKey, TValue> is thread-safe or not.

    Item[Object key]
    This property gets or sets a value associated with the specified key in theDictionary<TKey, TValue>.

    To use this property, you should not type Item, but you only need to specify the specific key within a pair of square brackets [ ]

    Keys
    This property gets an ICollection<TKey> containing the keys of aDictionary<TKey, TValue>.

    Values
    This property gets an ICollection<TValue containing the values of aDictionary<TKey, TValue>.






    Some methods in a Dictionary<TKey, TValue>.


    As Dictionary<TKey, TValue> implements Map interface, so some methods are inherited from Map.

    Methods Description
    int Add(TKey key, TValue value)
    This method adds the specified key-value pair in Dictionary<TKey, TValue>.

    bool Contains(TKey key)
    This method checks if Dictionary<TKey, TValue> contains a specific key.

    bool ContainsKey(TKey key)
    This method checks if Dictionary<TKey, TValue> contains a specific key.

    bool ContainsValue(TKey key)
    This method checks if Dictionary<TKey, TValue> contains a specific value.

    void Clear()
    This method removes all of the elements from the Dictionary<TKey, TValue>.

    int GetHash(TKey key)
    This method returns the hash code for the specified key.

    Dictionary<TKey, TValue>.Enumerator GetEnumerator()
    This method returns to enumerate the entire Dictionary<TKey, TValue>.

    void Remove(TKey key)
    This method removes the element with the specified key in the Dictionary<TKey, TValue>.






    Dictionary<TKey, TValue> example


    We will iterate over all the key-value pairs and we will also obtain a value on the basis its key.

    //C# Example of Dictionary<TKey, TValue>
    
    using System;
    using System.Collections.Generic;
    
    class DictionaryDemo
    {
    public static void Main(String[] ar)
    {
    	//Creating a Dictionary<TKey, TValue>
    	//Where, Keys are of type String
    	//And, Values are of type int
    	Dictionary<String, int> dict = new Dictionary<String, int>();
    
    	//Adding key-value pairs by the Add() method
    	dict.Add("Max", 1000);
    	dict.Add("John", 4000);
    	dict.Add("Tom", 2000);
    	dict.Add("Ana", 6000);
    	dict.Add("Rick", 5000);
    
    	//Getting a collection of the keys using property Keys
    	ICollection<String> c = dict.Keys;
    	
    	// Use the keys to obtain the values.
    	foreach(String str in c)
    		Console.WriteLine(str + ": " + dict[str]);
    
    	//Using the property Item to retrieve the value of key "Tom"
    	//Remember the property Item is not used with its name
    	Console.WriteLine("Value at the key, Tom is "+ dict["Tom"]);
    
    	//Using the property Item to retrieve the value of key "Ana"
    	Console.WriteLine("Value at the key, Ana is "+ dict["Ana"]);
    }
    }
    

    Output is :

    Max: 1000
    John: 4000
    Tom: 2000
    Ana: 6000
    Rick: 5000
    Value at the key, Tom is 2000
    Value at the key, Ana is 6000


    Program Analysis





    Advertisement




    Checking if Dictionary<TKey, TValue> contains a specific key or a specific value


    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement



    Notifications



    Please check our latest addition

    C#, PYTHON and DJANGO


    Advertisement