Welcome back! Now that we've explored lists in C#, you're ready to tackle another essential collection type: Sets. Sets provide a unique way to manage collections where item uniqueness is crucial. They are particularly useful in scenarios where you need to ensure no duplicates exist, just like ensuring each discovered planet is only listed once in our space registry.
In C#, sets are known as HashSet<T>
. So, whenever we mention sets, remember they are the same thing as HashSet
. 😉
Before we dive deeper, let's take a moment to understand the key differences between sets and lists in C#. Both are powerful, but they serve different purposes:
Add
and Remove
just like lists do, but with the added enforcement of uniqueness.So, imagine your collection as a space registry—use a set to ensure each planet is listed only once, ensuring efficiency and uniqueness!
In this lesson, you'll gain valuable skills for working with sets in C#. Specifically, you will:
HashSet
in C#.HashSet
.Here’s a quick example to set the stage:
C#1// Define a HashSet with 3 initial items 2HashSet<string> discoveredPlanets = new HashSet<string> { "Mercury", "Venus", "Earth" }; 3 4// Try to add a duplicated item 5discoveredPlanets.Add("Venus"); 6 7// Check if the item exists 8Console.WriteLine("Is planet in set: " + discoveredPlanets.Contains("Venus")); 9// Output: True 10 11// Count items in the HashSet 12Console.WriteLine("Number of planets: " + discoveredPlanets.Count); 13// Output: 3
Sets are powerful when it comes to ensuring the uniqueness of elements in your collections. Unlike lists, where duplicates are allowed, sets automatically enforce that all elements are unique. This makes sets ideal for tasks such as membership checks, managing inventories that must not have duplicate entries, and unique identifier collections. For instance, we can use sets to catalog new planets without worrying about listing the same planet more than once.
Are you ready to add this powerful tool to your programming toolkit? Let's dive into the practice section and start working with sets in C# together!