A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 5.3: Dictionaries

 A dictionary in C# is a collection of key-value pairs, where each key must be unique. It provides fast lookup and retrieval of values based on their associated keys. Here's a basic tutorial on using dictionaries in C#:

Creating a Dictionary

To use dictionaries in C#, you need to include the System.Collections.Generic namespace. Dictionaries are part of this namespace. You can create a dictionary using the Dictionary<TKey, TValue> class, where TKey is the type of the keys, and TValue is the type of the values.

using System;
using System.Collections.Generic;

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

        // Adding key-value pairs
        myDictionary.Add(1, "One");
        myDictionary.Add(2, "Two");
        myDictionary.Add(3, "Three");

        // Accessing values using keys
        Console.WriteLine(myDictionary[1]);  // Output: One

        // Iterating through key-value pairs
        foreach (var kvp in myDictionary)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

Dictionary Initialization

You can also initialize a dictionary with values directly:

Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
    {1, "One"},
    {2, "Two"},
    {3, "Three"}
};


Checking if a Key Exists

Before accessing a value using a key, it's a good practice to check if the key exists to avoid exceptions:

int keyToCheck = 4;

if (myDictionary.ContainsKey(keyToCheck))
{
    Console.WriteLine($"Value for key {keyToCheck}: {myDictionary[keyToCheck]}");
}
else
{
    Console.WriteLine($"Key {keyToCheck} not found");
}

Removing Items

You can remove items from a dictionary using the Remove method:

myDictionary.Remove(2); // Removes the key-value pair with key 2


Dictionary Methods

Dictionaries provide various methods for manipulation, such as ContainsKey, ContainsValue, Clear, Count, etc. Refer to the official documentation for a comprehensive list.

Dictionaries are a powerful data structure in C#, and they are commonly used when fast lookups based on keys are required.