Practical Application of Dictionaries in C#

Topic Overview

In this lesson, we will explore the concept and practical application of Dictionaries in C#. Dictionaries are a powerful and efficient data structure used for storing key-value pairs. You will learn how to utilize Dictionary to count the frequency of elements in a collection, understand the underlying mechanics, and analyze the time and space efficiency of this approach. This lesson includes a step-by-step demonstration with detailed code examples and a discussion on the practical applications of using Dictionaries for counting occurrences in various contexts.

Understanding the Problem

We begin in a library, where we want to count book copies. With a small collection, we might be able to tally each one manually. However, as the collection grows, this approach becomes cumbersome and inefficient. A more efficient method uses a Dictionary.

For a quick illustration, consider this list of colors:

using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        List<string> colors = new List<string> {
            "red",
            "blue",
            "red",
            "green",
            "blue",
            "blue"
        };
    }
}

If we count manually, red appears twice, blue appears thrice, and green appears once. We can employ Dictionaries for a more efficient counting process.

Introducing Dictionaries

Simple yet powerful, Dictionaries allow us to store and retrieve data using keys. The unique colors in our list act as keys, and the count of each color becomes its corresponding value. Let's demonstrate how we can count elements in our colors list using C#'s Dictionary:

using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        List<string> colors = new List<string> {
            "red",
            "blue",
            "red",
            "green",
            "blue",
            "blue"
        };

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

        // Start the loop to iterate over each color
        foreach (string color in colors) {

            // If the color is present in our Dictionary, increment its value by 1
            if (colorCount.ContainsKey(color)) {
                colorCount[color]++;
            } else {
                // If the color isn't present, it means we're encountering this color in our list for the first time.
                // In this case, we add it to our Dictionary and set its value to 1
                colorCount.Add(color, 1);
            }
        }

        // Print our Dictionary with counts
        foreach (var kvp in colorCount) {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

When the above code executes, it displays the counts for each color:

red: 2
green: 1
blue: 3
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