Dictionary Overview in C#

Dictionary in C#

  • Dictionary is a generic class that belongs to the System.Collection namespace in .NET.
  • The dictionary type in C# allows the user to retrieve a corresponding value very quickly for a specified key value.
  • A dictionary can store Keys and Values of any data type in .NET.
  • It provides a mapping from a set of keys to a set of values .
  • Represented as Dictionary<TKey, TValue> pair where TKey represents Key and TValue represents the value associated with the key.
  • Each Key in a Dictionary is associated with a corresponding Value.
  • Retrieving a value using its key is very fast, close to O(1), because the Dictionary<TKey, TValue> class is implemented as a hash table.
  • Each key in the dictionary must be unique and cannot be NULL but a value corresponding to a key can be NULL and/or a duplicate.
  • The capacity of a Dictionary<TKey, TValue> varies according to the number of elements present in the Dictionary.
  • As elements are added to a Dictionary<TKey, TValue>, the capacity is automatically increased as required by reallocating the internal array.
  • The maximum capacity of a dictionary is up to 2 billion elements on a 64-bit system by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.
  • Each item in the Dictionary can be iterated through KeyValuePair<TKey, TValue> structure representing a value and it's key.
  • In case of multiuser environment a Dictionary<TKey, TValue> can support multiple readers concurrently until the collection is modified even though enumerating through a collection is intrinsically not a thread-safe procedure.
  • In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration.
  • So if you have to iterate through each member of the collection use a List type but if have want to look up a value in a collection then always choose Dictionary.
  • Has better performance than any other type if the number of elements is large in a collection.
  • Almost the same performance as that of an array so sometimes an array and dictionary objects are interchangeable (refhttp://www.dotnetperls.com/array-dictionary-test).

Methods and Attributes with Example

1. Declaration

A Dictionary can be declared as follows:

  1. //If capacity of dictionary is not known    
  2. Dictionary<stringstring> dicObj = new Dictionary<stringstring>();    
  3.     
  4. //If capacity of dictionary is known    
  5. Dictionary<stringstring> dicObj = new Dictionary<stringstring>(5);    
2. Add()

This method is used to add elements with key value pair in the dictionary object.
  1. DicObj.Add("key1""val1");   
  2. DicObj.Add("key2"" val2");   
  3. DicObj.Add("key3"" val3");   
  4. DicObj.Add("key4"" val4");   
3. Reading or iterating through Dictionary element

Since the Dictionary type represents a collection so we can use the foreach loop to go through all the items and read them using they Key and Value properties.
  1. foreach (KeyValuePair<string, Int16> author in AuthorList)  
  2. {   
  3. Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);  
  4. }  
4. Remove()

This method is used to remove an element from a dictionary object.
  1. DicObj.Remove("key4");  
5. Clear()

This method removes all the elements from a dictionary object.
  1. DicObj.Clear();  
6. ContainsKey()

This method is used to find a key from the Dictionary and it returns a Boolean value indicating whether that key is found in the collection or not.
  1. if (!AuthorList.ContainsKey("key4"))   
  2. {   
  3. DicObj ["key4"] = 20;   
  4. }  
7. ContainsValue()

This method is used to check whether a value exists in the dictionary or not and it returns a Boolean value indicating whether that value is found in the collection or not.
  1. if (!AuthorList.ContainsValue("Value4"))   
  2. {   
  3. // write code here  
  4. }  
8. Keys

This attribute returns a collection of keys present in the dictionary object. It returns an object of KeyCollection type.
  1. Dictionary<stringstring>.KeyCollection keys = DicObj.Keys;   
  2. foreach (string key in keys)   
  3. {   
  4. // code to process keys   
  5. }  
9. Values

This attribute returns a collection of values present in the dictionary object. It returns an object of ValueCollection type.
  1. Dictionary<stringstring>.ValueCollection values = DicObj.Values;   
  2. foreach (string val in values)   
  3. {   
  4. // code to process values   
  5. }  
10. Item

The Item property is used to get and set the value associated with the specified key.
  1. // Set Item value  
  2. DicObj ["key4"] = value5;  
  3. // Get Item value  
  4. string value = DicObj ["key4];  
11. Count

This property is used to count the number of elements present in the dictionary at any time.
  1. Int noOfElements = DicObj.Count

Up Next
    Ebook Download
    View all
    Learn
    View all