Lesson 5
Using Dictionaries in C#
Introduction to Dictionaries

Welcome back! Now that we've explored sets in C#, it's time to introduce a new and powerful collection type: Dictionaries. Dictionaries provide a unique way to manage collections that map keys to values. They are incredibly useful when you need to quickly look up values based on a specific key, similar to looking up star data by their catalog numbers in our astronomical registry.

Understanding Dictionaries

We’ve talked about different types of collections like arrays, lists, and sets. Here's a brief reminder:

  • Arrays: Fixed-size collections that store elements of the same type.
  • Lists: Dynamic-size collections that also store elements of the same type, allowing for easy addition and removal of items.
  • Sets: Collections that ensure all elements are unique and ignore the order.

Dictionaries, unlike these collections, store elements as key-value pairs. Each key in a dictionary is unique, allowing you to quickly retrieve the corresponding value associated with that key. This makes dictionaries special and extremely efficient for look-up operations.

What You'll Learn

In this lesson, you'll gain valuable skills for working with dictionaries in C#. Specifically, you will:

  • Understand what a dictionary is and how it differs from arrays, lists, and sets.
  • Learn how to define and initialize a dictionary in C#.
  • Master techniques to add, remove, and look up items in a dictionary.

Here’s a quick example to get you started:

C#
1// Define a dictionary with initial key-value pairs 2Dictionary<string, int> planetMoons = new Dictionary<string, int> 3{ 4 { "Earth", 1 }, 5 { "Mars", 2 }, 6 { "Jupiter", 79 } 7}; 8 9// Add a key-value pair to the dictionary 10planetMoons.Add("Saturn", 83); 11 12// Print the added item 13Console.WriteLine($"Saturn has {planetMoons["Saturn"]} moons."); 14 15// Remove an item from the dictionary by key 16planetMoons.Remove("Mars"); 17 18// Check if the key was removed 19Console.WriteLine($"Is Mars still in the dictionary? {planetMoons.ContainsKey("Mars")}");
Why It Matters

Dictionaries are crucial for efficiently managing data pairs and performing quick look-ups based on unique keys. Whether you're implementing a system to catalog astronomical bodies or creating a phone book, dictionaries provide the optimal structure for these tasks. By mastering dictionaries, you’ll enhance the performance and organization of your programs, allowing you to manage data in a more structured way.

Excited to dive deeper and start using dictionaries in C#? Let's move on to the practice section and explore their practical applications together!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.