A comprehensive overview of Dictionary in C#

What is a Dictionary?

A dictionary is a collection type in C# that allows you to store key-value pairs. Each key in a dictionary is unique, and it is used to retrieve the associated value. This makes dictionaries an efficient data structure for looking up and retrieving values based on their keys. Think of it like a real-world dictionary where you look up words and find their meanings. In a C# dictionary, you use a key to look up a specific value.

Key Characteristics of Dictionaries

  1. Key-Value Pair: Each element in a dictionary consists of a key and an associated value. The key is used to uniquely identify the value.
  2. Uniqueness: Keys within a dictionary must be unique. You cannot have duplicate keys.
  3. Efficient Lookups: Dictionaries provide fast lookup times for retrieving values based on their keys. This makes them suitable for scenarios where quick access to values is essential.
  4. Dynamic Size: Dictionaries can grow or shrink as you add or remove key-value pairs.
  5. No Guarantee of Order: Dictionaries do not guarantee a specific order of key-value pairs. The order is not preserved as it is in arrays or lists.

"Imagine you're the manager of a small online store, and you want to keep track of products and their prices. You decide to use a digital system to handle this information. In this system, each product's name is like a key, and the price of the product is the value associated with that key. Similar to how customers would search for a product by its name to find its price on your website, in a C# dictionary, you use the product name as the key to quickly retrieve its price."

In this scenario, the online store's product database functions like a dictionary, where product names (keys) are utilized to efficiently find and display the corresponding price (value).

using System;
using System.Collections.Generic;

class OnlineStore
{
    static void Main()
    {
        Dictionary<string, double> productDatabase = new Dictionary<string, double>();

        // Manager adds products and their prices to the database
        productDatabase.Add("Laptop", 800.0);
        productDatabase.Add("Phone", 500.0);
        productDatabase.Add("Tablet", 300.0);
        productDatabase.Add("Headphones", 100.0);
        productDatabase.Add("Keyboard", 50.0);
        productDatabase.Add("Mouse", 20.0);
        productDatabase.Add("Monitor", 250.0);
        productDatabase.Add("Printer", 150.0);
        productDatabase.Add("Camera", 350.0);
        productDatabase.Add("Smartwatch", 200.0);

        // Customers search for products and see their prices
        CustomerSearch(productDatabase);

        // Manager can also access the database
        ManagerAccess(productDatabase);
    }

    static void CustomerSearch(Dictionary<string, double> database)
    {
        Console.WriteLine("Welcome to the Online Store!");
        Console.WriteLine("What product are you looking for?");
        string product = Console.ReadLine();

        if (database.ContainsKey(product))
        {
            double price = database[product];
            Console.WriteLine($"The price of {product} is ${price}");
        }
        else
        {
            Console.WriteLine("Product not found in the database.");
        }
    }

    static void ManagerAccess(Dictionary<string, double> database)
    {
        Console.WriteLine("\nManager's Access:");
        Console.WriteLine("Product Database:");

        foreach (var kvp in database)
        {
            Console.WriteLine($"Product: {kvp.Key}, Price: ${kvp.Value}");
        }
    }
}


--Output
Welcome to the Online Store!
What product are you looking for?
Headphones
The price of Headphones is $100

Manager's Access:
Product Database:
Product: Laptop, Price: $800
Product: Phone, Price: $500
Product: Tablet, Price: $300
Product: Headphones, Price: $100
Product: Keyboard, Price: $50
Product: Mouse, Price: $20
Product: Monitor, Price: $250
Product: Printer, Price: $150
Product: Camera, Price: $350
Product: Smartwatch, Price: $200

Creating Dictionaries

Creating dictionaries in C# involves declaring, initializing, and populating them with key-value pairs.  

Example 1. Declaring and Initializing Using Object Initializer.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Using object initializer to create and initialize a dictionary
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Aman", 25 },
            { "Saurav", 30 },
            { "Rajeev", 28 }
        };

        foreach (var kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

--Output

Aman: 25
Saurav: 30
Rajeev: 28

Example 2. Adding Key-Value Pairs After Initialization.

using System;
using System.Collections.Generic;

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

        // Adding key-value pairs after initialization
        ages["Ritest"] = 25;
        ages["Priya"] = 30;
        ages["suhani"] = 28;

        foreach (var kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

Example 3. Using Type Inference with var.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var ages = new Dictionary<string, int>
        {
            { "Abhinav", 25 },
            { "Pradeep", 30 },
            { "Avnish", 28 }
        };

        foreach (var kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

Example 4. Creating an Empty Dictionary and Adding Later.

using System;
using System.Collections.Generic;

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

        // Adding key-value pairs later
        ages.Add("virendra", 25);
        ages.Add("Sajeev", 30);
        ages.Add("Suhani", 28);

        foreach (var kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

Why Use Dictionaries?

Dictionaries are particularly useful when you need to quickly lookup values based on some unique identifier (the key). Here are some scenarios where dictionaries shine:

  • Caching: Storing cached data where the key is the input and the value is the computed result.
  • Data Indexing: Indexing large datasets for faster retrieval.
  • Configurations: Storing configuration settings where the key represents a setting name and the value is the corresponding value.
  • Mapping: Creating a mapping between two related pieces of data.

Dictionary Types in C#

1. Dictionary<TKey, TValue>

The Dictionary<TKey, TValue> class is the most commonly used dictionary type in C#. It allows you to store key-value pairs, where TKey represents the type of keys, and TValue represents the type of values. This class provides fast lookups and is suitable for general dictionary scenarios.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store song titles and their play counts
        Dictionary<string, int> songPlayCounts = new Dictionary<string, int>();

        // Adding songs and their play counts to the dictionary
        songPlayCounts["Imagine"] = 1000000;
        songPlayCounts["Bohemian Rhapsody"] = 750000;
        songPlayCounts["Shape of You"] = 2000000;
        songPlayCounts["Billie Jean"] = 500000;
        songPlayCounts["Smells Like Teen Spirit"] = 300000;

        // Retrieving play count of a specific song
        string songToCheck = "Shape of You";
        if (songPlayCounts.ContainsKey(songToCheck))
        {
            int playCount = songPlayCounts[songToCheck];
            Console.WriteLine($"The song '{songToCheck}' has been played {playCount} times.");
        }
        else
        {
            Console.WriteLine($"The song '{songToCheck}' is not found in the dictionary.");
        }
    }
}

--Output
The song 'Shape of You' has been played 2000000 times.

2. SortedDictionary<TKey, TValue>

The SortedDictionary<TKey, TValue> class is similar to the `Dictionary<TKey, TValue>`, but it maintains the keys in sorted order. This can be useful when you need key-value pairs sorted by keys.

using System;

namespace LibraryApp
{
    class Program
    {
        static void Main()
        {
            Library library = new Library();

            library.AddBook("Pride and Prejudice", 1813);
            library.AddBook("To Kill a Mockingbird", 1960);
            library.AddBook("1984", 1949);

            int publicationYear = library.GetPublicationYear("To Kill a Mockingbird");
            if (publicationYear != -1)
            {
                Console.WriteLine($"Publication Year: {publicationYear}");
            }
            else
            {
                Console.WriteLine("Book not found in the library.");
            }

            library.DisplayAllBooks();
        }
    }

  
        public class Library
        {
            private SortedDictionary<string, int> bookPublicationYears = new SortedDictionary<string, int>();

            public void AddBook(string title, int publicationYear)
            {
                bookPublicationYears.Add(title, publicationYear);
            }

            public int GetPublicationYear(string title)
            {
                if (bookPublicationYears.TryGetValue(title, out int publicationYear))
                {
                    return publicationYear;
                }
                else
                {
                    return -1; // Indicates book not found
                }
            }

            public void DisplayAllBooks()
            {
                Console.WriteLine("Library Catalog:");

                foreach (var kvp in bookPublicationYears)
                {
                    Console.WriteLine($"Title: {kvp.Key}, Publication Year: {kvp.Value}");
                }
            }
        }
    

}


--Output

Publication Year: 1960
Library Catalog:
Title: 1984, Publication Year: 1949
Title: Pride and Prejudice, Publication Year: 1813
Title: To Kill a Mockingbird, Publication Year: 1960

3. ConcurrentDictionary<TKey, TValue>

The ConcurrentDictionary<TKey, TValue> class is designed for multi-threaded scenarios where concurrent access to the dictionary is required. It provides thread-safe methods for adding, updating, and retrieving values.

using System;
using System.Collections.Concurrent;

namespace EcommerceMiniProject
{
    class Program
    {
        static void Main()
        {
            EcommerceMiniProject.EcommerceStore store = new EcommerceMiniProject.EcommerceStore();
            store.RunEcommerce();
        }
    }

    public class EcommerceStore
    {
        private ConcurrentDictionary<string, decimal> productPrices = new ConcurrentDictionary<string, decimal>();

        public void AddProduct(string productName, decimal price)
        {
            productPrices.TryAdd(productName, price);
        }

        public bool BuyProduct(string productName)
        {
            if (productPrices.TryRemove(productName, out _))
            {
                Console.WriteLine($"You have successfully bought {productName}.");
                return true;
            }
            else
            {
                Console.WriteLine($"Sorry, {productName} is not available.");
                return false;
            }
        }

        public void DisplayProducts()
        {
            Console.WriteLine("Products in the E-commerce Store:");

            foreach (var kvp in productPrices)
            {
                Console.WriteLine($"Product: {kvp.Key}, Price: {kvp.Value:C}");
            }
        }

        public void RunEcommerce()
        {
            AddProduct("Laptop", 800.0m);
            AddProduct("Phone", 500.0m);
            AddProduct("Tablet", 300.0m);

            DisplayProducts();

            BuyProduct("Laptop");
            BuyProduct("Smartwatch");

            DisplayProducts();
        }
    }
}

--Output
Products in the E-commerce Store:
Product: Tablet, Price: ? 300.00
Product: Laptop, Price: ? 800.00
Product: Phone, Price: ? 500.00
You have successfully bought Laptop.
Sorry, Smartwatch is not available.
Products in the E-commerce Store:
Product: Tablet, Price: ? 300.00
Product: Phone, Price: ? 500.00

4. ImmutableDictionary<TKey, TValue>

The ImmutableDictionary<TKey, TValue> class is part of the System.Collections.Immutable namespace and provides an immutable (unchangeable) dictionary. This is useful when you want to ensure that the dictionary's state does not change after it's created.

using System;
using System.Collections.Immutable;

namespace HotelBookingApp
{
    class Program
    {
        static void Main()
        {
            Hotel hotel = new Hotel();
            hotel.RunHotelBooking();
        }
    }

    public class Hotel
    {
        private ImmutableDictionary<string, bool> roomAvailability;

        public Hotel()
        {
            roomAvailability = ImmutableDictionary<string, bool>.Empty;
        }

        public void AddRoom(string roomNumber)
        {
            roomAvailability = roomAvailability.Add(roomNumber, true);
        }

        public bool BookRoom(string roomNumber)
        {
            if (roomAvailability.ContainsKey(roomNumber) && roomAvailability[roomNumber])
            {
                roomAvailability = roomAvailability.SetItem(roomNumber, false);
                Console.WriteLine($"Room {roomNumber} has been booked.");
                return true;
            }
            else
            {
                Console.WriteLine($"Sorry, Room {roomNumber} is not available.");
                return false;
            }
        }

        public void DisplayAvailableRooms()
        {
            Console.WriteLine("Available Rooms:");

            foreach (var kvp in roomAvailability)
            {
                if (kvp.Value)
                {
                    Console.WriteLine($"Room: {kvp.Key}");
                }
            }
        }

        public void RunHotelBooking()
        {
            AddRoom("101");
            AddRoom("102");
            AddRoom("103");

            DisplayAvailableRooms();

            BookRoom("101");
            BookRoom("102");
            BookRoom("104");

            DisplayAvailableRooms();
        }
    }
}

--Output
Available Rooms:
Room: 103
Room: 102
Room: 101
Room 101 has been booked.
Room 102 has been booked.
Sorry, Room 104 is not available.
Available Rooms:
Room: 103

5. HybridDictionary

The HybridDictionary class combines the functionality of a list and a dictionary. It automatically switches between using a ListDictionary and a Hashtable based on the number of elements.

using System;
using System.Collections;
using System.Collections.Immutable;
using System.Collections.Specialized;

namespace SocialMediaApp
{
    class Program
    {
        static void Main()
        {
            SocialMediaPlatform platform = new SocialMediaPlatform();
            platform.RunSocialMedia();
        }
    }

    public class SocialMediaPlatform
    {
        private HybridDictionary userFollowers;

        public SocialMediaPlatform()
        {
            userFollowers = new HybridDictionary();
        }

        public void AddUser(string username)
        {
            userFollowers.Add(username, 0); // Initial follower count is 0
        }

        public void FollowUser(string follower, string following)
        {
            if (userFollowers.Contains(follower) && userFollowers.Contains(following))
            {
                userFollowers[following] = (int)userFollowers[following] + 1;
                Console.WriteLine($"{follower} is now following {following}.");
            }
            else
            {
                Console.WriteLine("Invalid usernames.");
            }
        }

        public void DisplayUserFollowers()
        {
            Console.WriteLine("User Followers:");

            foreach (DictionaryEntry entry in userFollowers)
            {
                Console.WriteLine($"User: {entry.Key}, Followers: {entry.Value}");
            }
        }

        public void RunSocialMedia()
        {
            AddUser("Suresh");
            AddUser("Mahendra");
            AddUser("Ritika");
            AddUser("Bhumika");
            AddUser("Raman");
            AddUser("Siya");

            FollowUser("Suresh", "Bhumika");
            FollowUser("Mahendra", "Ritika");
            FollowUser("Raman", "Siya");

            DisplayUserFollowers();
        }
    }
}

--Output
Suresh is now following Bhumika.
Mahendra is now following Ritika.
Raman is now following Siya.
User Followers:
User: Suresh, Followers: 0
User: Mahendra, Followers: 0
User: Ritika, Followers: 1
User: Bhumika, Followers: 1
User: Raman, Followers: 0
User: Siya, Followers: 1

Note. These are some of the commonly used dictionary types in C#. The choice of dictionary type depends on your specific use case, including performance requirements, threading considerations, and whether you need ordered keys.

Dictionary Methods and Properties 

Some important methods and properties of the `Dictionary<TKey, TValue>` class in C#:

Methods

1. Add(TKey key, TValue value)

The Add method in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, is used to add a new key-value pair to the dictionary. The method requires a key and a value as parameters and adds them to the dictionary. If the key already exists, an exception might be thrown.

Syntax

dictionary.Add(key, value);

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store products and their prices
        Dictionary<string, decimal> productPrices = new Dictionary<string, decimal>();

        // Add key-value pairs using the Add method
        productPrices.Add("Laptop", 800.0m);
        productPrices.Add("Phone", 500.0m);
        productPrices.Add("Tablet", 300.0m);

        // Display the products and their prices
        foreach (var kvp in productPrices)
        {
            Console.WriteLine($"Product: {kvp.Key}, Price: {kvp.Value:C}");
        }
    }
}

2. Remove(TKey key)

The Remove method in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, is used to remove a key-value pair from the dictionary based on the provided key. If the key is found, the associated key-value pair is removed from the dictionary. 

Syntax

dictionary.Remove(key);

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store employee IDs and names
        Dictionary<int, string> employees = new Dictionary<int, string>();

        // Add employee IDs and names
        employees.Add(101, "Alice");
        employees.Add(102, "Bob");
        employees.Add(103, "Charlie");

        // Remove an employee using the Remove method
        int employeeIdToRemove = 102;
        bool removed = employees.Remove(employeeIdToRemove);

        if (removed)
        {
            Console.WriteLine($"Employee with ID {employeeIdToRemove} has been removed.");
        }
        else
        {
            Console.WriteLine($"Employee with ID {employeeIdToRemove} was not found.");
        }
    }
}

3. TryGetValue(TKey key, out TValue value)

The TryGetValue method in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, is used to retrieve the value associated with a given key from the dictionary. Unlike direct indexing (dictionary[key]), TryGetValue does not throw an exception if the key is not found; instead, it returns a boolean indicating success and an "out" parameter for the retrieved value.

Syntax

bool success = dictionary.TryGetValue(key, out TValue value);

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store Indian names and their meanings
        Dictionary<string, string> Names = new Dictionary<string, string>();

        // Add Indian names and their meanings to the dictionary
        Names.Add("Aarav", "Peaceful");
        Names.Add("Aditi", "Mother of gods");
        Names.Add("Kiran", "Ray of light");
        Names.Add("Anaya", "Caring");
        Names.Add("Rohan", "Ascending");

        // Name to lookup in the dictionary
        string nameToLookup = "Kiran";

        // Try to retrieve the meaning of the name using TryGetValue
        if (Names.TryGetValue(nameToLookup, out string meaning))
        {
            Console.WriteLine($"The name {nameToLookup} means '{meaning}'.");
        }
        else
        {
            Console.WriteLine($"The meaning of {nameToLookup} is not found in the dictionary.");
        }
    }
}

4. ContainsKey(TKey key)

The ContainsKey method in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, is used to check whether a specific key exists in the dictionary or not. It returns a boolean indicating whether the key is present in the dictionary.

Syntax

bool keyExists = dictionary.ContainsKey(key);

Example:-

       // Create a dictionary to store names and ages
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // Add key-value pairs
        ages.Add("Alice", 30);
        ages.Add("Bob", 25);

        // Check if a key exists using the ContainsKey method
        string nameToCheck = "Alice";
        if (ages.ContainsKey(nameToCheck))
        {
            Console.WriteLine($"{nameToCheck} exists in the dictionary.");
        }
        else
        {
            Console.WriteLine($"{nameToCheck} does not exist in the dictionary.");
        }

5. ContainsValue(TValue value)

The ContainsValue method in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, is used to check whether a specific value exists in the dictionary or not. It returns a boolean indicating whether the value is present in the dictionary.

Syntax

bool valueExists = dictionary.ContainsValue(value);

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store student IDs and names
        Dictionary<int, string> students = new Dictionary<int, string>();

        // Add student IDs and names
        students.Add(101, "Alia");
        students.Add(102, "Anuska");
        students.Add(103, "Tamana");

        // Check if a value exists using the ContainsValue method
        string nameToCheck = "Tamana";
        if (students.ContainsValue(nameToCheck))
        {
            Console.WriteLine($"{nameToCheck} exists in the students dictionary.");
        }
        else
        {
            Console.WriteLine($"{nameToCheck} does not exist in the students dictionary.");
        }
    }
}

6. Clear()

The Clear method in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, is used to remove all key-value pairs from the dictionary, effectively clearing its contents.

Syntax

dictionary.Clear();

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store products and their quantities
        Dictionary<string, int> shoppingCart = new Dictionary<string, int>();

        // Add products and their quantities to the cart
        shoppingCart.Add("Apple", 5);
        shoppingCart.Add("Banana", 3);
        shoppingCart.Add("Orange", 2);

        // Display the shopping cart before clearing
        Console.WriteLine("Shopping Cart before clearing:");
        foreach (var kvp in shoppingCart)
        {
            Console.WriteLine($"Product: {kvp.Key}, Quantity: {kvp.Value}");
        }

        // Clear the shopping cart
        shoppingCart.Clear();

        // Display the shopping cart after clearing
        Console.WriteLine("\nShopping Cart after clearing:");
        foreach (var kvp in shoppingCart)
        {
            Console.WriteLine($"Product: {kvp.Key}, Quantity: {kvp.Value}");
        }
    }
}

7. Keys

The Keys property in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, allows you to get a collection of all the keys present in the dictionary.

Syntax

ICollection<TKey> keysCollection = dictionary.Keys;

Examples

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store patient IDs and names
        Dictionary<int, string> patients = new Dictionary<int, string>();

        // Add patient IDs and names
        patients.Add(101, "Alice");
        patients.Add(102, "Bob");
        patients.Add(103, "Charlie");

        // Get a collection of patient IDs using the Keys property
        ICollection<int> patientIDs = patients.Keys;

        // Display the patient IDs
        Console.WriteLine("Patient IDs in the hospital:");
        foreach (var id in patientIDs)
        {
            Console.WriteLine($"Patient ID: {id}");
        }
    }
}

8. Values

The Values property in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, allows you to get a collection of all the values present in the dictionary.

Syntax

ICollection<TValue> valuesCollection = dictionary.Values;

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store room types and rates
        Dictionary<string, double> roomRates = new Dictionary<string, double>();

        // Add room types and rates
        roomRates.Add("Standard", 100.0);
        roomRates.Add("Deluxe", 150.0);
        roomRates.Add("Suite", 250.0);

        // Get a collection of room rates using the Values property
        ICollection<double> ratesCollection = roomRates.Values;

        // Display the room rates
        Console.WriteLine("Room Rates in the Hotel:");
        foreach (var rate in ratesCollection)
        {
            Console.WriteLine($"Rate: {rate:C}");
        }
    }
}

Properties

1. Count

The Count property in various dictionary implementations, like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, allows you to get the number of key-value pairs present in the dictionary.

Syntax

int numberOfPairs = dictionary.Count;

Example

        Dictionary<string, int> shoppingCart = new Dictionary<string, int>();

        // Add items to the shopping cart
        shoppingCart.Add("Product A", 2);
        shoppingCart.Add("Product B", 1);
        shoppingCart.Add("Product C", 5);

        // Get the count of items in the shopping cart using the Count property
        int itemCount = shoppingCart.Count;

2. Item[TKey key]

The Item[TKey key] syntax, also known as the indexer, in various dictionary implementations like Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and SortedDictionary<TKey, TValue>, allows you to access or modify the value associated with a specific key in the dictionary.

Syntax

TValue value = dictionary[key];         // Access the value
dictionary[key] = newValue;             // Modify the value

Example

using System;
using System.Collections.Generic;

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

        // Add initial inventory
        inventory.Add("Product A", 20);
        inventory.Add("Product B", 15);
        inventory.Add("Product C", 10);

        // Display the initial inventory
        Console.WriteLine("Initial Inventory:");
        foreach (var kvp in inventory)
        {
            Console.WriteLine($"Product: {kvp.Key}, Quantity: {kvp.Value}");
        }

        // Update inventory after sales using the indexer
        inventory["Product A"] -= 5;
        inventory["Product B"] -= 3;

        // Display the updated inventory
        Console.WriteLine("\nUpdated Inventory:");
        foreach (var kvp in inventory)
        {
            Console.WriteLine($"Product: {kvp.Key}, Quantity: {kvp.Value}");
        }

        // Add new products to the inventory using the indexer
        inventory["Product D"] = 8;
        inventory["Product E"] = 12;

        // Display the inventory after adding new products
        Console.WriteLine("\nInventory after adding new products:");
        foreach (var kvp in inventory)
        {
            Console.WriteLine($"Product: {kvp.Key}, Quantity: {kvp.Value}");
        }
    }
}

3. Comparer

The Comparer property in the SortedDictionary<TKey, TValue> class is used to get the IComparer<TKey> implementation that is used to compare keys in the sorted dictionary.

The Comparer property allows you to access the comparer that determines the order of keys in the sorted dictionary. If you don't provide a custom comparer when creating a SortedDictionary<TKey, TValue>, it will use the default comparer for the key type TKey.

Syntax

IComparer<TKey> comparer = sortedDictionary.Comparer;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a sorted dictionary for the kitchen pantry with case-insensitive sorting
        SortedDictionary<string, int> kitchenPantry = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase);

        // Add initial ingredients to the pantry
        kitchenPantry.Add("Flour", 500);
        kitchenPantry.Add("sugar", 250);
        kitchenPantry.Add("Salt", 100);
        kitchenPantry.Add("Milk", 750);

        // Access the comparer used for sorting
        IComparer<string> comparer = kitchenPantry.Comparer;

        // Display the pantry inventory in sorted order
        Console.WriteLine("Kitchen Pantry Inventory:");
        foreach (var kvp in kitchenPantry)
        {
            Console.WriteLine($"Ingredient: {kvp.Key}, Quantity: {kvp.Value} grams");
        }

        // Use the indexer to update ingredient quantities
        kitchenPantry["flour"] -= 100;
        kitchenPantry["SUGAR"] -= 50;

        // Display the updated pantry inventory
        Console.WriteLine("\nUpdated Kitchen Pantry Inventory:");
        foreach (var kvp in kitchenPantry)
        {
            Console.WriteLine($"Ingredient: {kvp.Key}, Quantity: {kvp.Value} grams");
        }

        // Check if a specific ingredient is available
        string ingredientToCheck = "Salt";
        if (kitchenPantry.ContainsKey(ingredientToCheck))
        {
            Console.WriteLine($"\n{ingredientToCheck} is available.");
        }
        else
        {
            Console.WriteLine($"\n{ingredientToCheck} is not available.");
        }
    }
}

Iterating Through Dictionaries

Using foreach loop with KeyValuePairs: This is the most common and convenient way to iterate through a dictionary's key-value pairs.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Shivam", 28 },
            { "Rahul", 35 },
            { "Abhilash", 42 },
            { "Aditya", 19 },
            { "Arun", 30 }, 
            { "Priya", 27 } 
        };

        Console.WriteLine("Iterating using foreach loop:");
        foreach (var kvp in ages)
        {
            Console.WriteLine($"Name: {kvp.Key}, Age: {kvp.Value}");
        }

        Console.WriteLine("\nIterating through keys and accessing values:");
        foreach (string name in ages.Keys)
        {
            int age = ages[name];
            Console.WriteLine($"Name: {name}, Age: {age}");
        }

        Console.WriteLine("\nIterating using KeyValuePair enumeration:");
        using (var enumerator = ages.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                var kvp = enumerator.Current;
                Console.WriteLine($"Name: {kvp.Key}, Age: {kvp.Value}");
            }
        }
    }
}


--Output
Iterating using foreach loop:
Name: Shivam, Age: 28
Name: Rahul, Age: 35
Name: Abhilash, Age: 42
Name: Aditya, Age: 19
Name: Arun, Age: 30
Name: Priya, Age: 27

Iterating through keys and accessing values:
Name: Shivam, Age: 28
Name: Rahul, Age: 35
Name: Abhilash, Age: 42
Name: Aditya, Age: 19
Name: Arun, Age: 30
Name: Priya, Age: 27

Iterating using KeyValuePair enumeration:
Name: Shivam, Age: 28
Name: Rahul, Age: 35
Name: Abhilash, Age: 42
Name: Aditya, Age: 19
Name: Arun, Age: 30
Name: Priya, Age: 27

Example of Building a social media application and you want to keep track of users and their follower counts using a dictionary. 

using System;
using System.Collections.Generic;

class SocialMediaApp
{
    static void Main(string[] args)
    {
        Dictionary<string, int> followerCounts = new Dictionary<string, int>();

        // Adding users and their follower counts to the dictionary
        followerCounts.Add("user1", 1000);
        followerCounts.Add("user2", 500);
        followerCounts.Add("user3", 750);
        followerCounts.Add("user4", 2000);

        // Checking if a user exists in the dictionary using ContainsKey
        string searchUser = "user3";
        if (followerCounts.ContainsKey(searchUser))
        {
            Console.WriteLine($"User '{searchUser}' found with {followerCounts[searchUser]} followers.");
        }
        else
        {
            Console.WriteLine($"User '{searchUser}' not found.");
        }

        // Trying to find a user that doesn't exist
        string nonExistentUser = "user5";
        if (followerCounts.ContainsKey(nonExistentUser))
        {
            Console.WriteLine($"User '{nonExistentUser}' found with {followerCounts[nonExistentUser]} followers.");
        }
        else
        {
            Console.WriteLine($"User '{nonExistentUser}' not found.");
        }
    }
}

--Output
User 'user3' found with 750 followers.
User 'user5' not found.

Simple console-based implementation that allows you to add items to the inventory, view the current inventory, and search for items.

using System;
using System.Collections.Generic;

class Program
{
    static Dictionary<string, int> inventory = new Dictionary<string, int>();

    static void Main()
    {
        bool continueManaging = true;

        while (continueManaging)
        {
            Console.WriteLine("Inventory Management System");
            Console.WriteLine("1. Add Item");
            Console.WriteLine("2. View Inventory");
            Console.WriteLine("3. Search Item");
            Console.WriteLine("4. Exit");
            Console.Write("Select an option: ");

            int choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
                case 1:
                    AddItem();
                    break;
                case 2:
                    ViewInventory();
                    break;
                case 3:
                    SearchItem();
                    break;
                case 4:
                    continueManaging = false;
                    Console.WriteLine("Exiting...");
                    break;
                default:
                    Console.WriteLine("Invalid choice. Please select a valid option.");
                    break;
            }

            Console.WriteLine();
        }
    }

    static void AddItem()
    {
        Console.Write("Enter item name: ");
        string itemName = Console.ReadLine();

        Console.Write("Enter quantity: ");
        int quantity = int.Parse(Console.ReadLine());

        if (inventory.ContainsKey(itemName))
        {
            inventory[itemName] += quantity;
        }
        else
        {
            inventory[itemName] = quantity;
        }

        Console.WriteLine("Item added to inventory.");
    }

    static void ViewInventory()
    {
        Console.WriteLine("Current Inventory:");

        foreach (var kvp in inventory)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }

    static void SearchItem()
    {
        Console.Write("Enter item name to search: ");
        string itemName = Console.ReadLine();

        if (inventory.ContainsKey(itemName))
        {
            Console.WriteLine($"{itemName}: {inventory[itemName]}");
        }
        else
        {
            Console.WriteLine("Item not found in inventory.");
        }
    }
}

--Output
Inventory Management System
1. Add Item
2. View Inventory
3. Search Item
4. Exit
Select an option: 1
Enter item name: Laptop
Enter quantity: 50
Item added to inventory.

Inventory Management System
1. Add Item
2. View Inventory
3. Search Item
4. Exit
Select an option: 2
Current Inventory:
Laptop: 50

Inventory Management System
1. Add Item
2. View Inventory
3. Search Item
4. Exit
Select an option: 1
Enter item name: mouse
Enter quantity: 4
Item added to inventory.

Inventory Management System
1. Add Item
2. View Inventory
3. Search Item
4. Exit
Select an option: 3
Enter item name to search: mouse
mouse: 4

Example to manage household items and their quantities using Dictionary.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> householdItems = new Dictionary<string, int>
        {
            { "Toilet Paper", 12 },
            { "Soap", 3 },
            { "Dish Soap", 1 },
            { "Towels", 6 },
            { "Trash Bags", 5 }
        };

        Console.WriteLine("Household Items Status:");

        foreach (var kvp in householdItems)
        {
            string item = kvp.Key;
            int quantity = kvp.Value;

            string status;

            if (quantity <= 0)
            {
                status = "Out of Stock";
            }
            else if (item == "Toilet Paper" && quantity < 3)
            {
                status = "Needs Replenishment";
            }
            else if (item == "Soap" && quantity < 1)
            {
                status = "Needs Replenishment";
            }
            else
            {
                status = "In Stock";
            }

            Console.WriteLine($"Item: {item}, Quantity: {quantity}, Status: {status}");

            // Check if item needs replenishment
            if (status == "Needs Replenishment")
            {
                Console.WriteLine($"*** {item} needs replenishment! ***");
            }
        }
    }
}


--Output
Household Items Status:
Item: Toilet Paper, Quantity: 12, Status: In Stock
Item: Soap, Quantity: 3, Status: In Stock
Item: Dish Soap, Quantity: 1, Status: In Stock
Item: Towels, Quantity: 6, Status: In Stock
Item: Trash Bags, Quantity: 5, Status: In Stock


Summary

Dictionaries are powerful tools for managing data in various scenarios, and understanding their usage can greatly enhance your programming capabilities.Dictionaries  are a fundamental data structure that provide an efficient and flexible way to store, retrieve, and manage data using key-value pairs.Dictionaries  are dynamic data structures that store key-value pairs, offering fast retrieval and manipulation of data. Utilizing the Dictionary<TKey, TValue> class, developers can efficiently add, access, and update items. Dictionaries are valuable for tasks like caching, indexing, and lookups, enhancing performance. They provide a crucial tool for managing data associations, combining keys and values for powerful data representation.

As you continue your C# programming Learning journey, a solid understanding of dictionaries will empower you to solve various challenges effectively.

If you encounter any issues or have further questions, feel free to let me know, and I'll be glad to assist!

Thank you for reading, and I hope this post has helped provide you with a better understanding and comprehensive overview of Dictionary in C#.

"Keep coding, keep innovating, and keep pushing the boundaries of what's possible!

Happy Coding!


Similar Articles