C# Dictionary

Introduction

The Dictionary<TKey, TValue> class in C# represents a collection of key/value pairs that are organized based on the hash code of the key. It is part of the System.Collections.Generic namespace and provides fast lookups, additions, and deletions. Dictionaries are ideal for scenarios where you need to associate keys with values and quickly retrieve values based on their keys.

Key Features of Dictionary<TKey, TValue>

  • Key-Value Pairs: Stores data in key/value pairs.
  • Fast Lookups: Provides O(1) average time complexity for lookups, additions, and deletions.
  • Type Safety: Enforces type safety, ensuring that keys and values are of specified types.
  • Dynamic Size: Automatically resizes as elements are added or removed.

Creating a Dictionary

Declaration and Initialization

You can declare and initialize a Dictionary<TKey, TValue> in several ways:

Example

using System;
using System.Collections.Generic;

namespace DictionaryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an empty dictionary
            Dictionary<int, string> employees = new Dictionary<int, string>();

            // Creating a dictionary with initial elements
            Dictionary<int, string> departments = new Dictionary<int, string>
            {
                { 1, "Human Resources" },
                { 2, "Finance" },
                { 3, "Engineering" }
            };

            // Adding elements to the dictionary
            employees.Add(101, "John Doe");
            employees.Add(102, "Jane Smith");
            employees.Add(103, "Sam Brown");

            // Displaying elements
            Console.WriteLine("Employees:");
            foreach (var kvp in employees)
            {
                Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
            }
        }
    }
}

Output

Employees:
ID: 101, Name: John Doe
ID: 102, Name: Jane Smith
ID: 103, Name: Sam Brown

Common Operations on Dictionary

Adding Elements

  • Add: Adds a key/value pair to the dictionary.
employees.Add(104, "Alice Johnson");

Removing Elements

  • Remove: Removes the key/value pair with the specified key from the dictionary. Returns true if the key was found and removed; otherwise, false.
bool isRemoved = employees.Remove(102); // true
  • Clear: Removes all key/value pairs from the dictionary.
employees.Clear();

Accessing Elements

  • Indexer: Accesses elements by their key.
string employeeName = employees[101];
  • ContainsKey: Checks if the dictionary contains the specified key. Returns true if the key is found; otherwise, false.
bool hasEmployee = employees.ContainsKey(101); // true
  • ContainsValue: Checks if the dictionary contains the specified value. Returns true if the value is found; otherwise, false.
bool hasName = employees.ContainsValue("John Doe"); // true

Iterating Through a Dictionary

You can iterate through a dictionary using a foreach loop.

Example

foreach (var kvp in employees)
{
    Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
}

Checking the Dictionary Size

  • Count: Gets the number of key/value pairs in the dictionary.
int count = employees.Count;

Practical Example

Let’s create a practical example where we use a Dictionary<TKey, TValue> to manage a collection of student grades, allowing the user to add, remove, and display grades.

Example

using System;
using System.Collections.Generic;

namespace StudentGradesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> studentGrades = new Dictionary<int, string>();

            // Adding student grades
            AddGrade(studentGrades, 1, "A");
            AddGrade(studentGrades, 2, "B+");
            AddGrade(studentGrades, 3, "A-");

            // Displaying student grades
            DisplayGrades(studentGrades);

            // Removing a student grade
            RemoveGrade(studentGrades, 2);

            // Displaying the updated student grades
            DisplayGrades(studentGrades);
        }

        static void AddGrade(Dictionary<int, string> grades, int studentId, string grade)
        {
            grades[studentId] = grade;
            Console.WriteLine($"Added grade for student {studentId}: {grade}");
        }

        static void RemoveGrade(Dictionary<int, string> grades, int studentId)
        {
            if (grades.Remove(studentId))
            {
                Console.WriteLine($"Removed grade for student {studentId}");
            }
            else
            {
                Console.WriteLine($"Student ID {studentId} not found");
            }
        }

        static void DisplayGrades(Dictionary<int, string> grades)
        {
            Console.WriteLine("Student Grades:");
            foreach (var kvp in grades)
            {
                Console.WriteLine($"Student ID: {kvp.Key}, Grade: {kvp.Value}");
            }
        }
    }
}

Output

Added grade for student 1: A
Added grade for student 2: B+
Added grade for student 3: A-
Student Grades:
Student ID: 1, Grade: A
Student ID: 2, Grade: B+
Student ID: 3, Grade: A-
Removed grade for student 2
Student Grades:
Student ID: 1, Grade: A
Student ID: 3, Grade: A-

Conclusion

The Dictionary<TKey, TValue> class in C# provides a powerful way to manage collections of key/value pairs with fast lookups, additions, and deletions. It is ideal for scenarios where you need to associate keys with values and retrieve values quickly based on their keys. Understanding how to use Dictionary<TKey, TValue> effectively can help you manage collections of data in your applications.

Leave a Comment

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

Scroll to Top