Data Structures in C#: Exploring Dictionaries

Welcome to our C# data structures revision! Today, we will delve deeply into C# Dictionaries. Much like a bookshelf, Dictionaries allow you to quickly select the book (value) you desire by reading its label (key). They are vital in C# for quickly accessing values using keys and for efficiently inserting and deleting keys. So, let's explore C# Dictionaries for a clearer understanding of these concepts.

Introduction to C# Dictionaries and Operations

Before diving into real-world applications, it’s essential to grasp the fundamentals of C# Dictionaries, a crucial data structure for storing data as key-value pairs. Understanding how to define and perform basic operations on them prepares us for more complex implementations.

In C#, keys in a Dictionary must be unique and immutable. Common types used as keys include strings, integers, enums, and any object that overrides the GetHashCode() and Equals() methods. This ensures the keys are suitable for fast lookups.

using System;
using System.Collections.Generic;

// Defining a Dictionary
Dictionary<string, int> ageDictionary = new Dictionary<string, int>();

// Adding entries
ageDictionary["Alice"] = 25;
ageDictionary["Bob"] = 30;
Console.WriteLine("After adding: ");
foreach (var entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// Updating entries
ageDictionary["Alice"] = 26; // Updates Alice's age
Console.WriteLine("\nAfter updating: ");
foreach (var entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// Retrieving values
int ageOfAlice = ageDictionary.ContainsKey("Alice") ? ageDictionary["Alice"] : -1;
Console.WriteLine($"\nAlice's Age: {ageOfAlice}");

// Removing entries
ageDictionary.Remove("Bob");
Console.WriteLine("\nAfter removing Bob: ");
foreach (var entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// Counting entries
int entryCount = ageDictionary.Count;
Console.WriteLine($"\nNumber of Entries: {entryCount}");
  • Defining a Dictionary: Use Dictionary<TKey, TValue> where TKey is the type for keys and TValue is the type for values.
  • Adding: Initial addition of entries, printed after insertion.
  • Updating: Demonstrates updating the existing entry by reassigning Alice's age.
  • Retrieving: Uses ContainsKey to check existence and retrieve values.
  • Removing: Uses the Remove method to delete entries.
  • Counting: Uses the Count property to get the number of entries.

Now that you're familiar with these operations, let's apply them in a PhoneBook class.

Implementing a PhoneBook with C# Dictionaries

Imagine storing your friend's contact info in such a way that allows you to search for your friend's name (the key) and instantly find their phone number (the value).

using System;
using System.Collections.Generic;

// Define the PhoneBook class
class PhoneBook 
{
    private Dictionary<string, string> contacts;

    public PhoneBook() 
    {
        // Initialize the Dictionary
        contacts = new Dictionary<string, string>();
    }

    public void AddContact(string name, string phoneNumber) 
    {
        // Add or update a contact
        contacts[name] = phoneNumber;
    }

    public string GetPhoneNumber(string name) 
    {
        // Retrieve a phone number or return "Not Found"
        return contacts.ContainsKey(name) ? contacts[name] : "Not Found";
    }
}

// Define the Program class containing the Main method
class Program
{
    static void Main(string[] args)
    {
        // Create a PhoneBook instance
        PhoneBook phoneBook = new PhoneBook();

        // Add contacts
        phoneBook.AddContact("Alice", "123-456-7890");
        phoneBook.AddContact("Bob", "234-567-8901");

        // Get and display phone numbers
        Console.WriteLine(phoneBook.GetPhoneNumber("Alice")); // Output: "123-456-7890"
        Console.WriteLine(phoneBook.GetPhoneNumber("Bobby")); // Output: "Not Found"
    }
}

In the above code, we create a PhoneBook class that uses a Dictionary to store contacts. As you can see, Dictionaries simplify the processes of adding, modifying, and accessing information with unique keys.

Operations in Dictionaries

C# Dictionaries enable a variety of operations for manipulating data, such as adding, retrieving, and deleting key-value pairs, and more. Understanding these operations is crucial for efficient data handling in C#.

To add or update entries in a Dictionary, you use index notation or the Add method. If the key exists, the value is updated; if not, a new key-value pair is added. This flexibility allows for dynamic updates and additions to the Dictionary without needing a predefined structure.

The TryGetValue method retrieves the value associated with a specific key. It provides a safe way to access values, returning a boolean indicating success, and outputting the value if the key exists.

Checking if a key exists in the Dictionary can be done using the ContainsKey method. This method returns a boolean value — true if the key exists in the Dictionary, and otherwise false. This is particularly useful for conditionally handling data based on its existence in the Dictionary.

Deleting an entry is done using the Remove method followed by the key. This operation removes the specified key-value pair from the Dictionary, which is essential for actively managing the contents of the Dictionary.

The Count property provides the number of key-value pairs present in the Dictionary. This is especially useful when you need to know the total number of entries in the Dictionary.

Let’s see how these operations work in the context of a TaskManager class:

using System;
using System.Collections.Generic;

// Define TaskManager class
class TaskManager
{
    private Dictionary<string, string> tasks;

    public TaskManager()
    {
        // Initialize with an empty Dictionary
        tasks = new Dictionary<string, string>();
    }

    public void AddUpdateTask(string taskName, string status)
    {
        // Add a new task or update an existing task
        tasks[taskName] = status;
    }

    public string GetTaskStatus(string taskName)
    {
        // Use a nullable string type for status to address potential nullability
        return tasks.TryGetValue(taskName, out string? status) ? status : "Not Found";
    }

    public void DeleteTask(string taskName)
    {
        // Removes a task using its name
        if (tasks.ContainsKey(taskName))
        {
            tasks.Remove(taskName);
        }
        else
        {
            Console.WriteLine($"Task '{taskName}' not found.");
        }
    }

    public int GetTaskCount()
    {
        // Returns the number of tasks in the TaskManager
        return tasks.Count;
    }
}

// Define Program class with Main method
class Program
{
    static void Main(string[] args)
    {
        // Create a TaskManager instance
        TaskManager myTasks = new TaskManager();

        // Add tasks and update them
        myTasks.AddUpdateTask("Buy Milk", "Pending");
        Console.WriteLine(myTasks.GetTaskStatus("Buy Milk"));  // Output: Pending

        myTasks.AddUpdateTask("Buy Milk", "Completed");
        Console.WriteLine(myTasks.GetTaskStatus("Buy Milk"));  // Output: Completed

        // Delete a task
        myTasks.DeleteTask("Buy Milk");
        Console.WriteLine(myTasks.GetTaskStatus("Buy Milk"));  // Output: Not Found

        // Add another task and get the count
        myTasks.AddUpdateTask("Clean House", "In Progress");
        Console.WriteLine(myTasks.GetTaskCount());  // Output: 1
    }
}

This example showcases how to leverage Dictionary operations in C# to effectively manage data by adding, updating, retrieving, deleting entries, and checking the number of entries through a simulated Task Manager application.

Looping Through Dictionaries

C# provides an elegant way to loop through Dictionaries using foreach loops. We can iterate through keys, values, or both simultaneously using specific constructs provided by the KeyValuePair<TKey, TValue> class.

  • Keys: To loop through all the keys in the Dictionary, you can use the Keys property.
  • Values: To loop through all the values in the Dictionary, you can use the Values property.
  • Entries: To loop through all key-value pairs in the Dictionary, you can use the foreach with KeyValuePair<TKey, TValue>.

Let's explore this in our Task Manager example:

using System;
using System.Collections.Generic;

class TaskManager {
    private Dictionary<string, string> tasks;

    public TaskManager() {
        tasks = new Dictionary<string, string>();
    }

    public void AddTask(string taskName, string status) {
        tasks[taskName] = status;
    }

    public void PrintAllTaskKeys() {
        foreach (string taskName in tasks.Keys) {
            Console.WriteLine(taskName);
        }
    }

    public void PrintAllTaskValues() {
        foreach (string status in tasks.Values) {
            Console.WriteLine(status);
        }
    }

    public void PrintAllEntries() {
        foreach (KeyValuePair<string, string> entry in tasks) {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        TaskManager myTasks = new TaskManager();
        myTasks.AddTask("Buy Milk", "Pending");
        myTasks.AddTask("Pay Bills", "Completed");

        myTasks.PrintAllTaskKeys();
        /* Output:
        Buy Milk
        Pay Bills
        */

        myTasks.PrintAllTaskValues();
        /* Output:
        Pending
        Completed
        */

        myTasks.PrintAllEntries();
        /* Output:
        Buy Milk: Pending
        Pay Bills: Completed
        */
    }
}

In this example, we use foreach loops to iterate over a dictionary's keys, values, and entries using the Keys, Values, and foreach constructs. This allows us to easily print all tasks in our task manager along with their statuses.

Nesting with Dictionaries

Nesting in Dictionaries involves storing Dictionaries within another Dictionary. It's useful when associating multiple pieces of information with a key. Let's see how this works in a Student Database example.

using System;
using System.Collections.Generic;

class StudentDatabase {
    private Dictionary<string, Dictionary<string, string>> students;

    public StudentDatabase() {
        students = new Dictionary<string, Dictionary<string, string>>();
    }

    public void AddStudent(string name, Dictionary<string, string> subjects) {
        students[name] = subjects;
    }

    public string GetMark(string name, string subject) {
        if (students.TryGetValue(name, out Dictionary<string, string>? subjects)) {
            return subjects.ContainsKey(subject) ? subjects[subject] : "N/A";
        }
        return "N/A";
    }

    public void PrintDatabase() {
        foreach (KeyValuePair<string, Dictionary<string, string>> student in students) {
            Console.WriteLine("Student: " + student.Key);
            foreach (KeyValuePair<string, string> subject in student.Value) {
                Console.WriteLine($"    Subject: {subject.Key}, Grade: {subject.Value}");
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        StudentDatabase studentDb = new StudentDatabase();
        studentDb.AddStudent("Alice", new Dictionary<string, string> { { "Math", "A" }, { "English", "B" } });

        Console.WriteLine(studentDb.GetMark("Alice", "English")); // Output: "B"
        Console.WriteLine(studentDb.GetMark("Alice", "History")); // Output: "N/A"
        studentDb.PrintDatabase();
        /* Output:
        Student: Alice
            Subject: Math, Grade: A
            Subject: English, Grade: B
        */
    }
}
Hands-on Example

Let's shift our focus to a more interactive and familiar scenario: managing a shopping cart in an online store. This hands-on example will demonstrate how Dictionaries can be used to map product names to their quantities in a shopping cart. You will learn how to add products, update quantities, and retrieve the total number of items in the cart.

Here’s how you can implement and manipulate a shopping cart using a C# Dictionary:

using System;
using System.Collections.Generic;

class ShoppingCart {

    private Dictionary<string, int> cart;

    public ShoppingCart() {
        cart = new Dictionary<string, int>();
    }

    public void AddProduct(string productName, int quantity) {
        if (cart.ContainsKey(productName)) {
            cart[productName] += quantity;
        } else {
            cart[productName] = quantity;
        }
    }

    public void RemoveProduct(string productName) {
        if (cart.ContainsKey(productName)) {
            cart.Remove(productName);
        } else {
            Console.WriteLine($"{productName} not found in your cart.");
        }
    }

    public void ShowCart() {
        if (cart.Count == 0) {
            Console.WriteLine("Your shopping cart is empty.");
        } else {
            foreach (KeyValuePair<string, int> entry in cart) {
                Console.WriteLine($"{entry.Key}: {entry.Value}");
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        ShoppingCart myCart = new ShoppingCart();

        myCart.AddProduct("Apples", 5);
        myCart.AddProduct("Bananas", 2);
        myCart.AddProduct("Apples", 3);

        myCart.ShowCart();
        /* Output:
        Apples: 8
        Bananas: 2
        */

        myCart.RemoveProduct("Bananas");
        myCart.ShowCart();
        /* Output:
        Apples: 8
        */
    }
}

This example showcases the practical application of Dictionaries to manage a dynamic dataset, such as an online shopping cart. By using product names as keys and their quantities as values, we achieve efficient and flexible data manipulation. This exercise provides a solid foundation for understanding how to handle complex data structures in real-world C# applications.

Lesson Summary and Practice

Well done! Today, we delved into C# Dictionaries and explored various operations on Dictionaries. We now invite you to get hands-on experience with the upcoming practice exercises. To master these concepts and hone your C# Dictionary skills, practice is key. Happy learning!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal