Supercharge Your Code: Mastering the C# Dictionary

Supercharge Your Code: Mastering the C# Dictionary

Imagine you're developing an application and need to store and retrieve data quickly and efficiently. A classic example would be a list of products where each product has a unique code. How would you ensure that, when searching for a product by code, you can find it instantly, even if your list has thousands of items?

This is precisely the kind of problem that the Dictionary in C# solves.


What is a Dictionary?

The Dictionary is a data structure that associates unique keys with values. Think of it as a list of "questions and answers," where the key is the question and the value is the answer. In the case of our product application, the key would be the product code, and the value would be the product’s name or description.

With a Dictionary, searching for any product, for example, by code 123, is almost instantaneous, regardless of the collection's size. This is because it uses a technique called hashing, which makes lookups extremely efficient.


How Does the Dictionary Solve Your Problem?

Consider this situation: you have a list of products and want to find one based on its code. Using some structuries, would require you to iterate through the entire list until you find the right item. Now imagine how long that would take if your list had thousands of products! With a Dictionary, the search is direct and fast.


Creating a Dictionary

Let’s start by creating a Dictionary that maps product codes (integers) to their names (strings):

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

Here, we’ve created a dictionary that associates a product code with its name.


Adding Products

Adding items to a Dictionary is easy:

products.Add(1, "Coffee");
products.Add(2, "Cookies");
products.Add(3, "Ice Cream");        

Now, you have three products stored. If you need to add more, you can do it effortlessly, and the collection ensures that each product code is unique.


Solving the Lookup Problem

If you need to find the name of the product with code 2, for example, simply access the Dictionary by the key:

string product = products[2]; // Returns "Cookies"        

The time it takes to find this item would be almost the same, whether there are 3 or 10,000 items.

Now imagine how much this boosts the efficiency of your application in terms of speed and performance!


Updating and Removing Products

Updating a value is also straightforward. If you want to update the name of the product with code 2, you simply assign a new value:

products[2] = "Biscuits"; // Updates the product name        

To remove a product, use the Remove method:

products.Remove(3); // Removes "Ice Cream"        


Useful Functions in Dictionary

In addition to adding, accessing, and removing items, the Dictionary offers several useful functions that make your life easier in day-to-day programming.


ContainsKey

Checks if a key exists in the dictionary:

bool exists = products.ContainsKey(1); // Returns true if key 1 exists
        


ContainsValue

Checks if a value exists in the dictionary:

bool valueExists = products.ContainsValue("Tea"); // Returns true if value "Tea" exists        


TryGetValue

A safe way to retrieve a value without throwing an exception if the key doesn’t exist:

if (products.TryGetValue(2, out string product))
{
    Console.WriteLine($"Product found: {product}");
}
else
{
    Console.WriteLine("Product not found");
}        


Keys and Values

You can access all keys or all values in the dictionary:

var keys = products.Keys; // Returns all keys
var values = products.Values; // Returns all values        


Count

Returns the number of key-value pairs in the dictionary:

int totalProducts = products.Count; // Returns the number of products in the dictionary        


Clear

Removes all items from the dictionary:

products.Clear(); // Removes all elements        


RemoveWhere (HashSet)

While not directly part of the Dictionary, if you're using HashSet as a value, you can use this function to remove elements based on a condition:

HashSet<string> categories = new HashSet<string> { "Beverage", "Food" };
categories.RemoveWhere(c => c.StartsWith("B"));        


OrderBy/ThenBy (LINQ)

Although the Dictionary is not ordered by default, you can order it by transforming the data into a list or using LINQ:

var orderedProducts = products.OrderBy(p => p.Key).ToList(); // Orders by product code        


ForEach (LINQ)

If you want to easily iterate over the Dictionary, you can use LINQ to perform actions on each item:

products.ToList().ForEach(p => Console.WriteLine($"{p.Key}: {p.Value}"));        


ToList

If you want to work with the dictionary as a list, you can easily convert it:

var productList = products.ToList();        


Combining Dictionary with Other Data Structures

You can make Dictionary even more powerful by combining it with other data structures. This can provide even more sophisticated solutions to complex problems.

Dictionary of Lists

A great example is a Dictionary where the values are lists. This can be useful in scenarios where a unique key needs to map to multiple items. For example, imagine you have product categories, where each category can have multiple products.

Dictionary<string, List<string>> categoryProducts = new Dictionary<string, List<string>>();

categoryProducts.Add("Beverages", new List<string> { "Coffee", "Tea", "Juice" });
categoryProducts.Add("Snacks", new List<string> { "Cookies", "Chips", "Popcorn" });        

Now you have a structure where a single category (key) contains multiple products (list of values).

To add more products to a category:

categoryProducts["Beverages"].Add("Soda");        


Dictionary of Dictionaries

You can also nest Dictionary inside another Dictionary. This is extremely useful when you need to organize data hierarchically. For example, you could have a Dictionary to store store sections, where the key is the section (like "Electronics") and the value is another Dictionary that maps product codes to their names.

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

store.Add("Electronics", new Dictionary<int, string> { { 101, "Phone" }, { 102, "Laptop" } });
store.Add("Clothing", new Dictionary<int, string> { { 201, "T-shirt" }, { 202, "Jeans" } });        

Now you have a structure organized by section and products. To access the name of a product in the "Electronics" section:

string electronicProduct = store["Electronics"][101]; // Returns "Phone"        


Dictionary and HashSet

Combining Dictionary with a HashSet is also powerful. The HashSet stores unique values and allows you to quickly check for the existence of an item. Imagine you're building an application that stores a list of customers who have purchased a particular product:

Dictionary<int, HashSet<string>> customersByProduct = new Dictionary<int, HashSet<string>>();

customersByProduct.Add(101, new HashSet<string> { "John", "Mary" });
customersByProduct[101].Add("Carlos"); // Adds a new customer to product 101        

With HashSet, you ensure there are no duplicates in the values and can quickly check for the existence of an item:

bool alreadyPurchased = customersByProduct[101].Contains("Mary"); // Returns true        


The Power of Simplicity and Flexibility

The Dictionary in C# is a powerful tool on its own, but combining it with other data structures can further expand its capacity to solve complex problems. By leveraging lists, nested dictionaries, or HashSet, you can efficiently organize data and ensure quick searches and manipulation.

Next time you face a problem involving data storage and retrieval, think about how the Dictionary can be the key to a fast, efficient, and powerful solution! 🙂

Vagner Nascimento

Software Engineer | Go (golang) | NodeJS (Javascrit) | AWS | Azure | CI/CD | Git | Devops | Terraform | IaC | Microservices | Solutions Architect

7mo

Insightful, thanks for sharing

Lucas Wolff

.NET Developer | C# | TDD | Angular | Azure | SQL

7mo

Dictionary in C# is a powerful option, it provides fast lookups, insertions, and deletions by utilizing a key-value pair structure and much more, thanks for sharing this article!

Jader Lima

Data Engineer | Azure | Azure Databricks | Azure Data Factory | Azure Data Lake | Azure SQL | Databricks | PySpark | Apache Spark | Python

7mo

Great !

Daivid Simões

Senior QA Automation Engineer | SDET | Java | Selenium | Rest Assured | Robot Framework | Cypress | Appium

7mo

Insightful

To view or add a comment, sign in

More articles by David Ayrolla dos Santos

Insights from the community

Others also viewed

Explore topics