C# Dictionary with Examples

In C#, Dictionary is a generic collection, generally used to store a collection of key/value data pairs organized by unique keys. The operation of Dictionary is very similar to that of the non-generic hashtable. The  System.Collection.Generic  namespace defines a dictionary in C#. It is dynamic in nature, which means that the size of the dictionary changes dynamically, allowing you to add or remove objects from the dictionary as needed.
Only strongly typed objects, key/value pairs of a given data type can be stored in a dictionary in C#.

C# Dictionary Characteristics

The following are the main points to keep in mind when using dictionaries in C#.

    • The dictionary in C# is a generic collection of key/value pairs organized by keys.
    • The dictionary class exists in the System.Collections.Generic namespace.
    • Duplicate keys are not allowed in the dictionary. If you try to use them, the compiler will throw an exception.
    • In a dictionary, A key must be unique and cannot be null, but a value can be if TValue is a reference type.
    • Dictionary values ​​can be accessed by passing the key associated with the indexer, for example, Dictionary [key].
    • You can only store the same types of elements in Dictionary as its strongly-typed generic collection,ie. Dictionary<TKey, TValue>.
    • Items are stored in the Dictionary as KeyValuePair objects.
    • The Dictionary class implements the IDictionary<TKey,TValue> Interface.
    • Using dictionaries in C# can avoid boxing and unboxing.

Syntax for declaring dictionay in C#

In C#, the syntax for declaring dictionaries is as follows.

Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();

Type Parameters Of Dictionary In C#

 TKey  – The type of key we pass in the dictionary.
 TValue  – The type of value we pass in the dictionary.

Example of adding keys and values ​​to a C# dictionary

Below is an example of how to add key/value pair elements to a dictionary object
To add items to the dictionary, you can use the Add method.

using System;
using System.Collections.Generic;

public class GenericDictionaryExample
{
    public static void Main(string[] args)
    {   
        // Create a new dictionary using int keys and string values.
        Dictionary<string, string> myDictionary = new Dictionary<string, string>();

        // Add elements to the dictionary object.
        myDictionary.Add("101", "Shekh Ali");
        myDictionary.Add("102", "Daniel");
        myDictionary.Add("103", "Doug Kennedy");
        myDictionary.Add("104", "Minhaj Ali");
        myDictionary.Add("105", "Suhail Ali");
        myDictionary.Add("106", "Deepak");

        // Accessing elements as KeyValuePair objects using foreach loop.
        Console.WriteLine($"Key  :  Values");
        foreach (KeyValuePair<string, string> element in myDictionary)
        {
            Console.WriteLine($"{element.Key} { element.Value} ");
        }
         Console.ReadLine();
    }

}
C# Dictionary key-value output

Get the collection of keys using Dictionary.Keys Property

The following code example shows how to use the   Keys  property to list keys in a dictionary.

A Dictionary.KeyCollection containing the keys in the Dictionary.

// To get the Key Collection, use the Keys property.

 Dictionary<string, string>.KeyCollection keyCollection = myDictionary.Keys;

        // The elements of the KeyCollection are strongly typed.

        Console.WriteLine($"*** keys ***");
        foreach (string key in keyCollection)
        {
            Console.WriteLine($"    {key}    ");
        }

image- C# Dictionary key property
image- C# Dictionary key collection

Get the collection of Values using Dictionary.Values Property

The  Values  ​​ property is use to gets a collection containing the values in the Dictionary.
It returns an object of the Dictionary.ValueCollection type.

The following code example shows how to use the Values property to enumerate the values ​​in a dictionary.

 // To get the values from dictionary, use the Values property.

 Dictionary<string, string>.ValueCollection ValueCollection = myDictionary.Values;

        // The elements of the ValueCollection are strongly typed.

        Console.WriteLine($"*** Values ***");
        foreach (string value in ValueCollection)
        {
            Console.WriteLine($"    {value}    ");
        }

image- C# Dictionary value collection output
C# Dictionary value collection output

Find a Key in a Dictionary using Dictionary.ContainsKey(TKey) Method

The ContainsKey method determines whether the dictionary contains the specified key.
If the Dictionary contains items with the specified key, It returns true; otherwise, false.

Note: If the key is null, an ArgumentNullException will be thrown, and if the requested key is not in the dictionary, a KeyNotFoundException will be thrown.

The following code example demonstrates how to use the ContainsKey method to test whether the key exists before calling the Add method.

// ContainsKey can be used to check keys before inserting
        // them into the dictionary in C#.
        if (!myDictionary.ContainsKey("107"))
        {
            myDictionary.Add("107", "Rajat Sharma");
            Console.WriteLine($"Value added for key = \"107\": {myDictionary["107"]}");
        }

        // Output:
        // Value added for key = "107": Rajat Sharma

Dictionary.ContainsValue(TValue) Method

The ContainsValue method determines whether the dictionary contains a specific value.
If the Dictionary contains an element with the specified value, it returns true; otherwise false.

The following code snippet checks to see if a value already exists.

// ContainsValue can be used to check if value exist in the dictionary
        
        if (myDictionary.ContainsValue("Shekh Ali"))      
            Console.WriteLine("Item found");     
        else
            Console.WriteLine("Item not found");
        // Output:
        // Item found

Dictionary.TryGetValue(TKey, TValue) Method

The TryGetValue method is a more efficient way to retrieve values ​​from the dictionary that often checks keys that are not in the dictionary.

Use the TryGetValue Method if you’re not sure whether the Dictionary object has a given key.
This method is a Boolean method with two parameters. The first is an input parameter called a key, and the second is an output parameter called a value. It will return the value if the dictionary object contains the specific key.

The following code snippet checks to see if a value already exists for a specific key.

// TryGetValue can be used to return the value if it exist in the dictionary

        string value = string.Empty;
        if (myDictionary.TryGetValue("102", out value))
            Console.WriteLine($"For key = \"102\", value = {value}.");

        else
            Console.WriteLine("Key = \"102\" is not found.");
       
        // Output:
        // For key = "102", value = Daniel.

Get total number of items in a C# dictionary

The Count property of a C# dictionary is used to get the total number of key/value pairs contained in the Dictionary.

Let’s write the following code snippets to display the total number of items in the dictionary.

// Count property returns the total numbers of items in the dictionary.

        Console.WriteLine($"Total Items: {myDictionary.Count}");

        // Output:
        // Total Items: 6

Dictionary<TKey,TValue>.Remove Method

The Remove() method is used to delete the value with the specified key from the Dictionary.
If the key is found and the item is successfully removed, it returns true; otherwise false.

The following code example demonstrates how to use the Remove method to remove key/value pairs from a dictionary.

// Use the Remove method to remove a key / value pair.
        Console.WriteLine("\nRemove(\"107\")\n");
        myDictionary.Remove("107");

        // Check if item is removed from the dictionary object.
        if (!myDictionary.ContainsKey("107"))
        {
            Console.WriteLine("Key \"107\" is not found.");
        }

image- C# Dictionary remove method output
image- C# Dictionary remove method output

Dictionary<TKey,TValue>.Clear Method

The Clear() method is used to delete all the keys and values items from the dictionary.
After removing all items from the dictionary object, the Count property will be set to 0.

The following code example demonstrates how to use the Clear() method to remove all the items from a dictionary.

Console.WriteLine($"\nTotal items count before calling Clear() method \n Count = {myDictionary.Count}");

  // Use the Clear method to remove all the items from the dictionary.
           myDictionary.Clear();

 Console.WriteLine($"\nTotal items count after calling Clear() method \n Count = {myDictionary.Count}");

The output of the above program is shown in the following snapshot:

image- C# Dictionary clear method output
image- C# Dictionary clear method output

Conclusion:

In this article, we learn about the Dictionary class in C# by looking at its description, syntax, workings, properties, and methods through multiple programming examples.

Recommended Articles

    1. Generic Delegates in C# With Examples
    2. IEnumerable Interface in C# with examples
    3. Constructors in C# with Examples
    4. Properties In C# with examples
    5. 10 Difference between interface and abstract class In C#
    6. Value Type and Reference Type in C#

Leave a Reply