I'm delighted to welcome you to our C# Sets lesson! In C#, sets are represented by the HashSet<T>
collection, which can only hold unique elements. They're particularly useful when you need to ensure that elements in a collection appear only once.
In this lesson, you'll consolidate your knowledge of creating and operating on sets using HashSet<T>
. You will learn about the advantages of using sets and how they enhance performance. Let's get started!
Let's begin by creating a set in C#. This can be done using the HashSet<T>
class.
C# provides methods to manipulate sets, such as Add
, Contains
, Remove
, and Clear
.
Add
: Adds a specified element to the set.Contains
: Checks if the specified element exists in the set.Remove
: Removes a specified element from the set.Clear
: Removes all elements from the set.
C# provides built-in methods for operations such as union, intersection, and difference for sets through LINQ.
Union
: Combines elements from both sets, excluding any duplicates. In this case, the result is a set containing{1, 2, 3, 4, 5, 6}
.Intersect
: Returns a set with only the elements that are common to both sets. For these sets, the intersection is{3, 4}
.Except
: Returns a set containing elements that are in the first set but not in the second set. Here, the result is{1, 2}
forset1
.
One of the key advantages of sets is their faster performance in membership tests, thanks to their use of hashing.
- Membership Test with
HashSet<T>
: Thanks to hash tables, sets can check for membership in constant time, leading to quick lookup times. The time taken for checking membership in the set is remarkably low. - Membership Test with List: Lists require a linear search to check for membership, which results in longer lookup times as the list grows. The time taken for checking membership in the list is noticeably higher.
Congratulations! You've just explored creating and manipulating sets, performing set operations, and reaping the performance benefits of sets in C#.
Remember, practice is key to solidifying your understanding. Happy coding!
