Dictionary In C#

Dictionary<TKey, TValue>

In this article, we will learn about the concept of  Dictionary<TKey, TValue> in C#.

  • The Dictionary<TKey, TValue> is a generic collection.
  • It generally stores data in key-value pairs in no particular order.
  • The working of Dictionary is quite similar to the non-generic hashtable.

The main characteristic of the Dictionary are:

  • The Dictionary<TKey, TValue> stores data in a key-value pair.
  • The Dictionary<TKey, TValue> Comes under System.Collections.Generic namespace.
  • It Implements IDictionary<TKey, TValue> interface.
  • Keys of Dictionary<TKey, TValue> must be unique and cannot be null.
  • Values of Dictionary<TKey, TValue> can be null or duplicate.
  • A value can be accessed by passing the associated key in the indexer.
  • All elements are stored as KeyValuePair<TKey, TValue> objects.

Properties

1. Comparer

Gets the IEqualityComparer<T> that is used to determine the equality of keys for the dictionary.

2. Count

Gets the total number of key/value pairs contained in the Dictionary<TKey, TValue>.

3. Item[TKey]

Gets or sets the value of Dictionary<TKey, TValue> associated with the specified key.

4. Keys

It will get a collection/elements containing the keys in the Dictionary<TKey, TValue>.

5. Values

It will get a collection/elements containing the values in the Dictionary<TKey, TValue>.

Methods

1. Add(TKey, TValue)

It will add a specified key and value to the Dictionary<TKey, TValue>.

2. Clear()

It will remove all keys and values from the Dictionary<TKey, TValue>.

3. ContainsKey(TKey)

It will determine whether the Dictionary<TKey, TValue> contains the specified key or not.

4. ContainsValue(TValue)

It will determine whether the Dictionary<TKey, TValue> contains a specific value or not.

5. EnsureCapacity(Int32)

It will ensure that the Dictionary<TKey, TValue> can hold up to a specified number of entries without any further expansion of its backing storage.

6. Equals(Object)

It will determine whether the specified object is equal to the current object or not.

7. GetEnumerator()

It will return an enumerator that iterates through the Dictionary<TKey, TValue>.

8. GetHashCode()

It serves as the default hash function.

9. GetObjectData(SerializationInfo, StreamingContext)

It Implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance.

10. GetType()

It is used to get the Type of the current instance.

11. MemberwiseClone()

It will create a shallow copy of the current Object.

12. OnDeserialization(Object)

It implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

13. Remove(TKey)

It removes the value with the specified key from the Dictionary<TKey, TValue>.

14. Remove(TKey, TValue)

It removes the value with the specified key from the Dictionary<TKey, TValue>, and copies the element to the value parameter.

15. ToString()

It will return a string that represents the current object.

16. TrimExcess()

It will set the capacity of this dictionary to what it would be if it had been originally initialized with all its entries.

17. TrimExcess(Int32)

It will set the capacity of this dictionary to hold up a specified number of entries without any further expansion of its backing storage.

18. TryAdd(TKey, TValue)

Attempts to add the specified key and value to the Dictionary<TKey, TValue>.

19. TryGetValue(TKey, TValue)

It will get the value associated with the specified key.

Example

using System;
using System.Collections.Generic;

namespace DictionaryExample
{
    class Program
    {
        static void Main(string[] args)
        {

            //Creating a Dictionary object

            Dictionary<string, string> Phones = new Dictionary<string, string>();

            //Adding elements in to Dictionary object
            Phones.Add("Nokia", "Nokia 3310");
            Phones.Add("Apple", "Iphone 11, Iphone 12");
            Phones.Add("Samsung", "samsung s20, Samsung s21 ultra");
            Phones.Add("Oppo", "Oppo Reno7");

            //Phones.Add("Oppo","Oppo A3s"); //Dictionary will not allow you to add duplicate key
            
            //Phones.Add(null, "Oppo A3s"); //Dictionary will not allow you to add null key

            Phones.Add("","Realme 6"); //Dictionary will allow empty key

            Phones.Add("Vivo",""); //Dictionary will allow empty or null value

            //Display all Elements in Dictionary object after Add
            Console.WriteLine("\n\t-----Display elements after Adding-----");
            foreach (KeyValuePair<string,string> keyValue in Phones)
            {
                Console.WriteLine("\n\t Key : {0}  -  Value : {1}", keyValue.Key,keyValue.Value);
            }
        }
    }
}

The output of the above example,

As we see in the above example, Dictionary will not allow you to add a duplicate or null key. If we try to add then it will give a compile-time error as below,

But as we see in the example, Dictionary will allow us to add empty and null values.

Example of removing an element,

//Remove element from Dictionary
Phones.Remove("Nokia");

//Display all Elements after Remove
Console.WriteLine("\n\t-----Display elements after Remove-----");
foreach (KeyValuePair<string, string> keyValue in Phones)
{
    Console.WriteLine("\n\t Key : {0}  -  Value : {1}", keyValue.Key, keyValue.Value);
}

The output of the above example,

Example of how to update the element value,

//Update element of Dictionary Object
if (Phones.ContainsKey("Oppo"))
{
    Phones["Oppo"] = "Oppo findX, Oppo f19 Pro+, Oppo F21 Pro";
}

//Display all Elements after Update
Console.WriteLine("\n\t-----Display elements after Update-----");
foreach (KeyValuePair<string, string> keyValue in Phones)
{
    Console.WriteLine("\n\t Key : {0}  -  Value : {1}", keyValue.Key, keyValue.Value);
}

The output of the above example,

Advantages

  • It’s a generic type.
  • It is dynamic in nature. It means the size of the Dictionary<TKey, TValue> grows according to the need.
  • You don’t need to limit the size of the Dictionary<TKey, TValue> to achieve good performance, because retrieving a value by using its key is very fast.

Disadvantages

  • We can not specify the values in the design-time like Datatable, Action parameters, and environment variable.

I hope this article will help you to understand the concept of Dictionary<TKey, TValue> in C#

Thank you.

Also check, Hashtable In C#.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories