C# Dictionary Usage: Complete Guide with Examples

C# Dictionary Usage: Complete Guide with Examples

A Dictionary in C# is a collection that stores data as key-value pairs. Each key is unique and is used to access its corresponding value quickly. The Dictionary<TKey, TValue> class is part of the System.Collections.Generic namespace and is optimized for fast lookups.

Think of a dictionary like a real-world dictionary:

• Key → Word
• Value → Meaning

1. What is a Dictionary in C#?

A Dictionary allows you to:

• Store data with a unique key
• Retrieve values quickly using the key
• Organize data efficiently

Basic Example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> ages = new Dictionary<string, int>();

        ages.Add("Alice", 25);
        ages.Add("Bob", 30);

        Console.WriteLine(ages["Alice"]); // Output: 25
    }
}

2. Creating and Initializing a Dictionary

Syntax:

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

Example with Initialization:

Dictionary<string, string> countries = new Dictionary<string, string>
{
    { "TR", "Turkey" },
    { "US", "United States" },
    { "DE", "Germany" }
};

3. Adding Elements

Using Add() Method:

countries.Add("FR", "France");

Using Index Syntax:

countries["IT"] = "Italy";

4. Accessing Values

Console.WriteLine(countries["TR"]); // Output: Turkey

• If the key does not exist, this will throw an error.

5. Safe Access with TryGetValue()

if (countries.TryGetValue("US", out string value))
{
    Console.WriteLine(value);
}
else
{
    Console.WriteLine("Key not found");
}

6. Checking Keys and Values

countries.ContainsKey("TR");   // true or false
countries.ContainsValue("Germany"); // true or false

7. Removing Elements

countries.Remove("DE"); // Removes Germany
countries.Clear();      // Removes all items

8. Iterating Through a Dictionary

Using foreach:

foreach (KeyValuePair<string, string> item in countries)
{
    Console.WriteLine(item.Key + " - " + item.Value);
}

Simplified Version:

foreach (var item in countries)
{
    Console.WriteLine($"{item.Key} => {item.Value}");
}

Common Dictionary Methods

Here is a quick overview of frequently used dictionary methods:

Method Description
Add() Adds a new key-value pair
Remove() Removes a key-value pair by key
ContainsKey() Checks if a key exists
ContainsValue() Checks if a value exists
TryGetValue() Safely gets a value without throwing an error
Clear() Removes all elements
Count Gets total number of elements

10. Real-World Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<int, string> students = new Dictionary<int, string>
        {
            { 1, "Ali" },
            { 2, "Ayşe" },
            { 3, "Mehmet" }
        };

        Console.WriteLine("Student List:");

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

11. Advantages and Disadvantages

Advantages:

• Fast lookup (O(1) average)
• Organized key-value structure
• Flexible and widely used

Disadvantages:

• Keys must be unique
• Slightly more memory usage
• No guaranteed order (unless using special types)

12. Dictionary vs List

Feature Dictionary List
Access Method Accessed by key Accessed by index
Lookup Speed Very fast (O(1) average) Slower (O(n) search)
Data Structure Key-value pairs Single values
Ordering No guaranteed order Maintains insertion order
Duplicate Handling Keys must be unique Allows duplicate values
Use Case Fast data lookup by key Ordered collection of items

13. Common Mistakes

• Accessing a non-existing key
• Adding duplicate keys
• Not using TryGetValue() for safe access
• Confusing dictionary with list

14. Best Practices

• Use meaningful keys
• Use TryGetValue() instead of direct access when unsure
• Avoid duplicate key logic errors
• Use var in loops for cleaner code