Understanding Dictionary in C#

Introduction

In C#, a Dictionary is a powerful collection type that stores key-value pairs. It provides efficient lookup, insertion, and deletion operations based on keys. Understanding how to use dictionaries can greatly enhance your ability to manage and manipulate data efficiently in C#.

What is a Dictionary?

A Dictionary in C# is a collection type from the System.Collections.Generic namespace that stores a collection of key-value pairs. Each key must be unique within the dictionary, and it's used to access its associated value.

Basic Operations with Dictionary


1. Creating a Dictionary

To create a dictionary in C#, we must define the type for keys (TKey) and values (TValue). Here's an example.

// Creating a Dictionary with string keys and int values
Dictionary<string, int> ages = new Dictionary<string, int>();

2. Adding Elements to Dictionary

We can add elements to the dictionary using the Add() method or by using the indexer ([]) if the key does not already exist.

// Adding elements to the dictionary
ages.Add("Rajesh", 30);
ages.Add("Amit", 35);
ages["Vikram"] = 25; // Using indexer to add

3. Accessing Values

Retrieve values from the dictionary by specifying the associated key using the indexer.

// Accessing values
Console.WriteLine($"Rajesh's age is: {ages["Rajesh"]}");

4. Checking for Key Existence

To check if a key exists in the dictionary, we can use the ContainsKey() method.

// Checking key existence
if (ages.ContainsKey("Amit"))
{
    Console.WriteLine("Amit's age exists in the dictionary.");
}

5. Iterating Through a Dictionary

We can iterate through the key-value pairs in a dictionary using a foreach loop.

// Iterating through the dictionary
foreach (var pair in ages)
{
    Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}

Example Demonstrating Dictionary Usage

Consider an example where a dictionary is used to store the count of occurrences of elements in an array.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a Dictionary with string keys and int values
        Dictionary<string, int> ageMap = new Dictionary<string, int>();

        // Adding key-value pairs to the dictionary
        ageMap.Add("Siddharth", 25);
        ageMap.Add("Aarav", 30);
        ageMap.Add("Aditi", 28);
	    ageMap.Add("Rahul", 35);

        // Accessing values using keys
        Console.WriteLine($"Aditi's age: {ageMap["Aditi"]}");

        // Checking if a key exists
        if (ageMap.ContainsKey("Siddharth"))
        {
            Console.WriteLine($"Siddharth's age: {ageMap["Siddharth"]}");
        }

        // Iterating through key-value pairs
        foreach (var pair in ageMap)
        {
            Console.WriteLine($"{pair.Key}'s age is {pair.Value}");
        }

        // Removing a key-value pair
        ageMap.Remove("Rahul");

        // Clearing the dictionary
        ageMap.Clear();
    }
}

Key Features of Dictionary

  • Key-Value Structure: The Dictionary stores data in a key-value format, enabling fast retrieval of values based on their associated keys.
  • Unique Keys: Each key in a Dictionary must be unique. Adding a duplicate key will result in an exception.
  • Efficient Lookup: Under the hood, dictionaries use hash tables, providing O(1) time complexity for lookup operations.
  • Adding and Removing Elements: We can easily add and remove key-value pairs using the Add and Remove methods.
  • Iterating Through a Dictionary: Iterating through a dictionary allows you to access and process each key-value pair using loops like foreach.
  • Memory Efficiency: Efficiently manages memory, optimizing the storage of key-value pairs for faster access.
  • Generic Support: Utilizes generics, ensuring type safety for keys and values, and preventing type mismatches.
  • Value Modifications: Allows modification of values associated with keys, offering flexibility in updating stored data.

Advanced Operations


Handling Key Existence

To safely access a value in a dictionary without risking an exception, we can use the TryGetValue method.

if (ageMap.TryGetValue("Aarav", out int aaravAge))
{
    Console.WriteLine($"Aarav's age: {aaravAge}");
}

This method attempts to retrieve the value associated with the specified key. If the key exists, it returns true and assigns the value to the out parameter.

Checking Dictionary Size

We can get the number of elements in a dictionary using the Count property:

Console.WriteLine($"Number of elements in the dictionary: {ageMap.Count}");

Conclusion

The Dictionary in C# is a versatile collection type that offers efficient storage and retrieval of key-value pairs. Understanding its usage and various methods will empower you to manage data effectively within your C# applications. Whether it's handling mappings, configuration settings, or any scenario requiring key-based data storage, the Dictionary is an invaluable tool in your C# programming.


Similar Articles