C# | HashSet Class
A HashSet<T> is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list.
Characteristics of HashSet Class:
- The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
- The capacity of a HashSet<T> object is the number of elements that the object can hold.
- A HashSet<T> object’s capacity automatically increases as elements are added to the object.
- A HashSet<T> collection is not sorted and cannot contain duplicate elements.
- HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction.
Constructors
Constructor | Description |
---|---|
HashSet() | Initializes a new instance of the HashSet class that is empty and uses the default equality comparer for the set type. |
HashSet(IEnumerable) | Initializes a new instance of the HashSet class that uses the default equality comparer for the set type, contains elements copied from the specified collection, and has sufficient capacity to accommodate the number of elements copied. |
HashSet(IEnumerable, IEqualityComparer) | Initializes a new instance of the HashSet class that uses the specified equality comparer for the set type, contains elements copied from the specified collection, and has sufficient capacity to accommodate the number of elements copied. |
HashSet(IEqualityComparer) | Initializes a new instance of the HashSet class that is empty and uses the specified equality comparer for the set type. |
HashSet(Int32) | Initializes a new instance of the HashSet class that is empty, but has reserved space for capacity items and uses the default equality comparer for the set type. |
HashSet(Int32, IEqualityComparer) | Initializes a new instance of the HashSet class that uses the specified equality comparer for the set type, and has sufficient capacity to accommodate capacity elements. |
HashSet(SerializationInfo, StreamingContext) | Initializes a new instance of the HashSet class with serialized data. |
Example:
// C# code to create a HashSet
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of odd numbers
HashSet<int> odd = new HashSet<int>();
// Inserting elements in HashSet
for (int i = 0; i < 5; i++) {
odd.Add(2 * i + 1);
}
// Displaying the elements in the HashSet
foreach(int i in odd)
{
Console.WriteLine(i);
}
}
}
Output:
1 3 5 7 9