C# Dictionaries

What is 'Dictionary' in C#?

Dictionary

A dictionary is a collection type that stores key-value pairs where each key must be unique within the dictionary. Dictionaries are part of the 'System.Collections.Generic' namespace and are implemented by the Dictionary'<TKey, TValue>' class.

Brief overview of the concept:

1. Key-Value Pair: Each entry in a dictionary consists of a key and a corresponding value. The key is used to access the associated value. Keys are typically of immutable types like strings, integers, or custom objects.

2. Unique Keys: Every key in a dictionary must be unique. Adding a key-value pair with a key that already exists in the dictionary will overwrite the existing value.

3. Fast Lookup: Dictionaries provide fast lookup times for values based on their keys. This is achieved through hash tables, which allow for constant-time average complexity for accessing elements by key.

4. Dynamic Size: Dictionaries in C# can dynamically resize to accommodate more elements as needed, so you don't need to specify the size beforehand.

5. Iterating Over Elements: You can iterate over the key-value pairs in a dictionary using various methods like 'foreach' loops or 'LINQ' methods.

Demonstrating the usage of dictionaries:

cs Copy Code
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a new dictionary
        Dictionary<string, int> ageDictionary = new()
        {
            // Adding key-value pairs
            ["Ayan"] = 28,
            ["Sanvi"] = 25,
            ["Apu"] = 23
        };

        // Accessing values by key
        Console.WriteLine("Ayan's age: " + ageDictionary["Ayan"]);

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

        // Checking if a key exists
        string name = "Ayan";
        if (ageDictionary.ContainsKey(name))
        {
            Console.WriteLine($"\n{name} exists in the dictionary.");
        }
        else
        {
            Console.WriteLine($"\n{name} doesn't exist in the dictionary.");
        }
    }
}                                
Output:
Ayan's age: 28
Ayan's age is 28
Sanvi's age is 25
Apu's age is 23

Ayan exists in the dictionary.

This example demonstrates creating a dictionary to store ages of individuals, accessing values by key, iterating over key-value pairs, and checking if a key exists in the dictionary.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.