Master C# Dictionary: Complete guide

May 13, 2023 | .NET, C#

Are you ready to dive into the world of C# dictionaries and optimize your code with fast and efficient data storage techniques? Let’s get our hands dirty with some advanced C# programming!

Introduction to C# Dictionary

C# dictionaries are powerful data structures that offer many benefits and can improve the way we write code. In this section, we will explore the concept of dictionaries in C# and some of their most common use cases.

What is a Dictionary in C#

A dictionary in C# is a collection of key-value pairs, where each key is unique and associated with one value. It can be thought of as a sort of virtual table where you can quickly look up values based on their keys. They are a part of the System.Collections.Generic namespace and are a central component when working with collections in C#.

// Initialize a dictionary with keys and values
var example = new Dictionary<string, int> {
  { "Apple", 1 },
  { "Banana", 2 },
  { "Cherry", 3 }
};

C# Dictionary Example

Now that we understand what a dictionary in C# is, let’s take a closer look at an example of how to declare and work with a dictionary.

Dictionary<string, int> phonebook = new Dictionary<string, int>();
phonebook.Add("John", 123456789);
phonebook.Add("Jane", 987654321);

In the code snippet above, we create a dictionary called phonebook with a string representing the name, and an integer representing their phone number. We then add two people, John and Jane, along with their phone numbers.

Variants of C# Dictionaries

C# offers several variants of dictionaries that provide different capabilities, such as sorted collections or collections optimized for concurrent access. Some examples include SortedDictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, and ReadOnlyDictionary<TKey, TValue>.

Creating and Initializing C# Dictionary

Creating and initializing a dictionary is a fundamental aspect of working with this data structure in C#. In this section, we will discuss different ways to create and initialize dictionaries and dive into various techniques available for dictionary initialization.

Creating a Dictionary in C#

To create a dictionary in C#, we first define the dictionary and then initialize it. The following code example demonstrates how to create a dictionary with keys and values using various techniques.

// Method 1: Using the constructor
Dictionary<string, int> dictionary1 = new Dictionary<string, int>();

// Method 2: Using Collection initializer syntax
Dictionary<string, int> dictionary2 = new Dictionary<string, int> {
  { "A", 1 },
  { "B", 2 },
  { "C", 3 }
};

// Method 3: Using the LINQ extension method `ToDictionary`
var list = new List<string> { "A", "B", "C" };
Dictionary<string, int> dictionary3 = list.ToDictionary(x => x, x => x.Length);

Initializing a Dictionary with Values

When you create a dictionary, you may also want to initialize it with some predefined key-value pairs. In C#, you can utilize the dictionary initializer to accomplish this task.

// Initialize a dictionary with predefined key-value pairs
var fruitBasket = new Dictionary<string, int> {
  { "Apple", 5 },
  { "Banana", 7 },
  { "Cherry", 3 }
};

Dictionary Initializers in C#

Starting with C# 6.0, you can use dictionary initializers to populate your dictionaries more elegantly. This syntax allows you to add keys and values by separating the key and the value with a colon, making it more apparent that you are working with key-value pairs.

Dictionary<string, double> exchangeRates = new Dictionary<string, double> {
  ["USD"] = 1.00,
  ["EUR"] = 0.84,
  ["JPY"] = 110.39
};

Creating a New Dictionary

When you need to create a new dictionary from an existing one, you can use the ToDictionary method or simply create a new instance by passing the existing dictionary as a constructor argument.

// Using ToDictionary
var originalDictionary = new Dictionary<string, int> { { "A", 1 }, { "B", 2 } };
var newDictionary1 = originalDictionary.ToDictionary(entry => entry.Key, entry => entry.Value);

// Using the constructor
var newDictionary2 = new Dictionary<string, int>(originalDictionary);

C# to Dictionary Example

Converting existing data structures like lists or arrays into dictionaries can be quite useful. With LINQ, you can easily convert data structures into a dictionary using the ToDictionary method.

List<string> countries = new List<string> { "USA", "Canada", "Mexico" };

// Convert the list to a dictionary with the country name as the key and the length of the name as the value
Dictionary<string, int> countryLengths = countries.ToDictionary(country => country, country => country.Length);

Working with C# Dictionary

In this section, we will take a closer look at how to work with dictionaries in C#. We’ll learn about some of the essential operations, such as adding and retrieving items, setting values, and working with keys.

Understanding Dictionary Keys

When working with dictionaries, it’s crucial to understand the importance of unique keys. Keys allow you to quickly access the values stored in the dictionary, while also ensuring that each entry has a unique identifier.

  • Keys must be unique within the same dictionary.
  • Keys cannot be null.
  • Adding a duplicate key to a dictionary will result in an ArgumentException.
  • You can iterate through the keys in a dictionary using the Keys property.
Dictionary<string, int> scores = new Dictionary<string, int>();

// Adding unique keys, this is correct
scores.Add("Alice", 90);
scores.Add("Bob", 85);

// Adding a duplicate key, this would throw an exception
try {
  scores.Add("Alice", 95);
} catch (ArgumentException e) {
  Console.WriteLine("Duplicate key detected!");
}

// Iterating through dictionary keys
foreach (string key in scores.Keys) {
  Console.WriteLine($"{key}: {scores[key]}");
}

Adding Items to a Dictionary

To add items to a dictionary, we can use the Add method, which takes two arguments: the key and the associated value. Keep in mind that the keys must be unique and cannot be null.

// Create and initialize a dictionary
Dictionary<string, int> products = new Dictionary<string, int>();

// Add items to the dictionary
products.Add("Laptop", 1500);
products.Add("Mouse", 20);

// Trying to add an item with an existing key would throw an exception
try {
  products.Add("Mouse", 25);
} catch (ArgumentException e) {
  Console.WriteLine("Duplicate key detected!");
}

Getting Values from a Dictionary

To retrieve a value from a dictionary, we can use the .TryGetValue method, which takes two arguments: the key and an out parameter for the associated value.

Dictionary<string, int> inventory = new Dictionary<string, int> {
  { "Apple", 10 },
  { "Banana", 15 }
};

int stock;
if (inventory.TryGetValue("Apple", out stock)) {
  Console.WriteLine($"Apples in stock: {stock}");
} else {
  Console.WriteLine("Apple not found in inventory.");
}

A more straightforward way to access the dictionary value by key is using the indexer. However, if the key is not found, it will throw a KeyNotFoundException.

try {
  int appleStock = inventory["Apple"];
  Console.WriteLine($"Apples in stock: {appleStock}");
} catch (KeyNotFoundException e) {
  Console.WriteLine("Apple not found in inventory.");
}

Retrieving Key-Value Pairs from a Dictionary

When we need to work with both keys and values, we can iterate through the key-value pairs using the KeyValuePair<TKey, TValue> structure.

foreach (KeyValuePair<string, int> kvp in inventory) {
  Console.WriteLine($"Item: {kvp.Key}, Stock: {kvp.Value}");
}

IDictionary Interface in C#

The IDictionary<TKey, TValue> interface is a more generic representation of dictionaries, which you can implement using different underlying data structures. By working with the IDictionary interface, your code can be more flexible and adaptable to other collection types.

IDictionary<int, string> students = new Dictionary<int, string>();
students.Add(1, "John");
students.Add(2, "Jane");
students.Add(3, "Jim");

Setting Dictionary Values

To update the values associated with dictionary keys, you can use the indexer notation.

Dictionary<string, int> productPrices = new Dictionary<string, int> {
  { "Laptop", 1500 },
  { "Mouse", 20 }
};

// Update the price of a laptop
productPrices["Laptop"] = 1400;

C# Dictionary Methods and Techniques

C# dictionaries offer various methods and techniques that help us perform different operations efficiently. In this section, we will discuss these techniques, such as initializing a dictionary with specific values, creating dictionaries with values, and using dictionary keys in different ways.

Common Dictionary Methods

Some commonly used dictionary methods include:

  • Add – Adds a key-value pair to the dictionary.
  • ContainsKey – Determines if the dictionary contains a specific key.
  • TryGetValue – Retrieves the value of the given key, returning true if the key is present, false otherwise.
  • Remove – Removes the key-value pair identified by the given key.
  • Clear – Removes all keys and values from the dictionary.

Initializing a Dictionary with Specific Values

To initialize a dictionary with specific values, you can use the collection initializer syntax.

Dictionary<string, double> grades = new Dictionary<string, double> {
  {"Math", 86.5},
  {"English", 95.0},
  {"History", 78.5}
};

Working with Key-Value Pairs

To work with key-value pairs in a dictionary, iterate through the dictionary using a KeyValuePair<TKey, TValue> structure.

foreach (KeyValuePair<string, double> grade in grades) {
  Console.WriteLine($"Subject: {grade.Key}, Score: {grade.Value}");
}

Converting a Dictionary to a String

To convert a dictionary into a string representation, you can use a StringBuilder or string.Join method.

StringBuilder sb = new StringBuilder();
foreach (var kvp in grades) {
  sb.AppendLine($"{kvp.Key}: {kvp.Value}");
}
string gradesStr = sb.ToString();
Console.WriteLine(gradesStr);

Or, with string.Join method:

string gradesStr = string.Join(Environment.NewLine, grades.Select(kvp => $"{kvp.Key}: {kvp.Value}"));
Console.WriteLine(gradesStr);

Using TryGetValue Method

The TryGetValue method can be quite useful when working with dictionaries, as it allows you to efficiently check for the presence of a key, and, if present, retrieve its value without causing an exception.

double mathGrade;
if (grades.TryGetValue("Math", out mathGrade)) {
  Console.WriteLine($"Math grade: {mathGrade}");
} else {
  Console.WriteLine("Math grade not found.");
}

Ordering a Dictionary

To reorder a dictionary based on key or value, we can use LINQ methods like OrderBy and OrderByDescending.

// Order by keys
var orderedByKey = grades.OrderBy(x => x.Key);
// Order by values descending
var orderedByValue = grades.OrderByDescending(x => x.Value);

Creating and Initializing a Dictionary with Values

You can create and initialize a dictionary with pre-defined values using the dictionary initializer syntax, as shown below:

Dictionary<string, int> studentAges = new Dictionary<string, int> {
  {"Alice", 19},
  {"Bob", 20},
  {"Charlie", 18}
};

Accessing Dictionary Keys

To access the keys of a dictionary or perform operations only on the keys, you can use the Keys property.

foreach (string key in studentAges.Keys) {
  Console.WriteLine(key);
}

Conclusion

In conclusion, C# dictionaries are a powerful tool for developers, offering efficient data storage and retrieval capabilities. From creating and initializing dictionaries to managing key-value pairs, the rich set of methods and techniques available make working with C# dictionaries a breeze. Remember to utilize the features discussed in this article whenever you work with dictionaries and enjoy the perks of high-performance and organized code!

You May Also Like

Sign up For Our Newsletter

Weekly .NET Capsules: Short reads for busy devs.

  • NLatest .NET tips and tricks
  • NQuick 5-minute reads
  • NPractical code snippets
.