The HashSet<T> collection
A set is a collection that contains only distinct items that can be in any order. .NET provides the HashSet<T>
class for working with sets. This class contains methods to handle the elements of the set but also methods to model mathematical set operations such as union or intersection.
Like all the other collections, HashSet<T>
contains several overloaded constructors that allow us to create either an empty set or a set filled with initial values. To declare an empty set, we use the default constructor (which is the constructor without parameters):
HashSet<int> numbers = new HashSet<int>();
But we can also initialize the set with some values, as shown in the following example:
HashSet<int> numbers = new HashSet<int>() { 1, 1, 2, 3, 5, 8, 11 };
To work with a set, we can use the following methods:
Add()
adds a new element to the set if the element is not already present...