The Dictionary<TKey, TValue>
class in C# is an essential collection in the System.Collections.Generic
namespace. It’s an ideal data structure for storing key-value pairs where fast retrieval of data based on unique keys is critical. This tutorial will cover the basics of Dictionary<TKey, TValue>
, provide examples and use cases, and discuss a real-world application to demonstrate its practical use.
Dictionary<TKey, TValue>
Dictionary<TKey, TValue>
is a powerful collection that enables storing data as key-value pairs. Unlike arrays or lists, a dictionary is a non-sequential collection, meaning it doesn’t store elements in any particular order. Instead, it uses a hash table to provide quick lookups, making it ideal for scenarios where data retrieval based on unique keys is essential.
O(1)
average time complexity for retrieval.Dictionary<TKey, TValue>
Creating a dictionary requires specifying types for both keys and values. You can initialize a dictionary with or without predefined key-value pairs.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating an empty dictionary with string keys and int values
Dictionary<string, int> ages = new Dictionary<string, int>();
// Initializing a dictionary with initial values
Dictionary<int, string> employees = new Dictionary<int, string>
{
{ 101, "Alice" },
{ 102, "Bob" },
{ 103, "Charlie" }
};
}
}
You can add elements to a dictionary using the Add
method. If a key already exists, an exception will be thrown.
ages.Add("John", 25);
ages.Add("Emma", 30);
To retrieve values, you can use the key as an index. If the key doesn’t exist, it will throw a KeyNotFoundException
, so using TryGetValue
is a safer approach.
// Accessing an existing key
int age = ages["John"];
// Using TryGetValue to avoid exceptions
if (ages.TryGetValue("Emma", out int emmaAge))
{
Console.WriteLine($"Emma's age is {emmaAge}");
}
You can update the value associated with an existing key by assigning a new value to it.
ages["John"] = 26; // Updates John's age to 26
To remove elements, use the Remove
method. It will remove the specified key and its associated value from the dictionary.
ages.Remove("Emma"); // Removes Emma from the dictionary
// Clearing all elements
ages.Clear(); // Removes all elements
Suppose we have an application that needs to manage employee information, where each employee has a unique ID, and we need quick access to employee names based on their IDs.
using System;
using System.Collections.Generic;
public class EmployeeDirectory
{
private Dictionary<int, string> employeeDirectory = new Dictionary<int, string>();
public void AddEmployee(int id, string name)
{
if (!employeeDirectory.ContainsKey(id))
{
employeeDirectory.Add(id, name);
Console.WriteLine($"Added Employee: {name}, ID: {id}");
}
else
{
Console.WriteLine($"Employee with ID {id} already exists.");
}
}
public void UpdateEmployee(int id, string newName)
{
if (employeeDirectory.ContainsKey(id))
{
employeeDirectory[id] = newName;
Console.WriteLine($"Updated Employee ID {id} to new name: {newName}");
}
else
{
Console.WriteLine($"Employee with ID {id} not found.");
}
}
public void DisplayEmployees()
{
Console.WriteLine("\nEmployee Directory:");
foreach (var employee in employeeDirectory)
{
Console.WriteLine($"ID: {employee.Key}, Name: {employee.Value}");
}
}
}
public class Program
{
public static void Main()
{
EmployeeDirectory directory = new EmployeeDirectory();
// Adding employees
directory.AddEmployee(101, "Alice");
directory.AddEmployee(102, "Bob");
// Displaying employees
directory.DisplayEmployees();
// Updating an employee's name
directory.UpdateEmployee(102, "Robert");
// Displaying employees again
Console.WriteLine("\nAfter updating Bob to Robert:");
directory.DisplayEmployees();
}
}
EmployeeDirectory
class encapsulates a Dictionary<int, string>
to store employee IDs as keys and names as values.AddEmployee
method ensures that each employee ID is unique.UpdateEmployee
method checks for the existence of an employee ID before updating the name.DisplayEmployees
method iterates through the dictionary, printing each employee’s ID and name.This structure enables quick lookups, additions, and updates, ideal for managing employee data based on unique identifiers.
Dictionary<TKey, TValue>
class provides fast lookups and is ideal for managing data that requires unique keys.The Dictionary<TKey, TValue>
class in C# is a versatile and efficient collection that makes managing and retrieving key-value pairs straightforward. With its unique key constraint and fast lookup capability, it’s perfect for applications like employee directories, configuration settings, and other scenarios requiring quick access to data. By understanding its features, how to add, access, and update elements, and practical applications, developers can utilize Dictionary<TKey, TValue>
to streamline data management in their C# applications. Whether handling IDs, settings, or other key-based data, Dictionary<TKey, TValue>
provides an organized, efficient solution.