HashSet<T>
Class
Definition
Represents a set of values.
public class HashSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
- T
The type of elements in the hash set.
- Inheritance
-
HashSet<T>
- Implements
Inherited Members
System.Object
Examples
The following example demonstrates how to merge two disparate sets. This example creates two HashSet<T> objects, and populates them with even and odd numbers, respectively. A third HashSet<T> object is created from the set that contains the even numbers. The example then calls the UnionWith method, which adds the odd number set to the third set.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}
/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
Imports System
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim evenNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()
Dim oddNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()
For i As Integer = 0 To 4
' Populate evenNumbers with only even numbers.
evenNumbers.Add(i * 2)
' Populate oddNumbers with only odd numbers.
oddNumbers.Add((i * 2) + 1)
Next i
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count)
DisplaySet(evenNumbers)
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count)
DisplaySet(oddNumbers)
' Create a new HashSet populated with even numbers.
Dim numbers As HashSet(Of Integer) = New HashSet(Of Integer)(evenNumbers)
Console.WriteLine("numbers UnionWith oddNumbers...")
numbers.UnionWith(oddNumbers)
Console.Write("numbers contains {0} elements: ", numbers.Count)
DisplaySet(numbers)
End Sub
Private Shared Sub DisplaySet(ByVal coll As HashSet(Of Integer))
Console.Write("{")
For Each i As Integer In coll
Console.Write(" {0}", i)
Next i
Console.WriteLine(" }")
End Sub
End Class
' This example produces output similar to the following:
' evenNumbers contains 5 elements: { 0 2 4 6 8 }
' oddNumbers contains 5 elements: { 1 3 5 7 9 }
' numbers UnionWith oddNumbers...
' numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
Remarks
Note
To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.
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.
Note
HashSet<T> implements the IReadOnlyCollection<T> interface starting with the .NET Framework 4.6; in previous versions of the .NET Framework, the HashSet<T> class did not implement this interface.
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.
The HashSet<T> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey,TValue> or Hashtable collections. In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey,TValue> collection without values.
A HashSet<T> collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the List<T> class together with the Sort method.
HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction. The following table lists the provided HashSet<T> operations and their mathematical equivalents.
| HashSet(Of T) operation | Mathematical equivalent |
|---|---|
| UnionWith | Union or set addition |
| IntersectWith | Intersection |
| ExceptWith | Set subtraction |
| SymmetricExceptWith | Symmetric difference |
In addition to the listed set operations, the HashSet<T> class also provides methods for determining set equality, overlap of sets, and whether a set is a subset or superset of another set.
For very large HashSet<T> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.
Starting with the .NET Framework 4, the HashSet<T> class implements the ISet<T> interface.
HashSet and LINQ Set Operations
LINQ provides access to the Distinct, Union, Intersect and Except set operations on any data source that implements the IEnumerable or IQueryable interfaces. HashSet<T> provides a larger and more robust collection of set operations. For example, HashSet<T> provides comparisons such as IsSubsetOf and IsSupersetOf.
The primary difference between LINQ set operations and HashSet<T> operations is that LINQ set operations always return a new IEnumerable<T> collection, whereas the HashSet<T> equivalent methods modify the current collection.
Typically, if you must create a new set or if your application needs access only to the provided set operations, using LINQ set operations on any IEnumerable<T> collection or array will be sufficient. However, if your application requires access to additional set operations, or if it is not desirable or necessary to create a new collection, use the HashSet<T> class.
The following table shows the HashSet<T> operations and their equivalent LINQ set operations.
| HashSet(Of T) operation | LINQ equivalent |
|---|---|
| UnionWith | Union |
| IntersectWith | Intersect |
| ExceptWith | Except |
| Not provided. | Distinct |
| SymmetricExceptWith | Not provided. |
| Overlaps | Not provided. |
| IsSubsetOf | Not provided. |
| IsProperSubsetOf | Not provided. |
| IsSupersetOf | Not provided. |
| IsProperSupersetOf | Not provided. |
| SetEquals | Not provided. |
Constructors
| HashSet<T>() |
Initializes a new instance of the HashSet<T> class that is empty and uses the default equality comparer for the set type. |
| HashSet<T>(IEnumerable<T>) |
Initializes a new instance of the HashSet<T> 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<T>(IEqualityComparer<T>) |
Initializes a new instance of the HashSet<T> class that is empty and uses the specified equality comparer for the set type. |
| HashSet<T>(Int32) | |
| HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) |
Initializes a new instance of the HashSet<T> 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<T>(Int32, IEqualityComparer<T>) | |
| HashSet<T>(SerializationInfo, StreamingContext) |
Initializes a new instance of the HashSet<T> class with serialized data. |
Properties
| Comparer |
Gets the IEqualityComparer<T> object that is used to determine equality for the values in the set. |
| Count |
Gets the number of elements that are contained in a set. |
Methods
| Add(T) |
Adds the specified element to a set. |
| Clear() |
Removes all elements from a HashSet<T> object. |
| Contains(T) |
Determines whether a HashSet<T> object contains the specified element. |
| CopyTo(T[]) |
Copies the elements of a HashSet<T> object to an array. |
| CopyTo(T[], Int32) |
Copies the elements of a HashSet<T> object to an array, starting at the specified array index. |
| CopyTo(T[], Int32, Int32) |
Copies the specified number of elements of a HashSet<T> object to an array, starting at the specified array index. |
| CreateSetComparer() |
Returns an IEqualityComparer object that can be used for equality testing of a HashSet<T> object. |
| ExceptWith(IEnumerable<T>) |
Removes all elements in the specified collection from the current HashSet<T> object. |
| GetEnumerator() |
Returns an enumerator that iterates through a HashSet<T> object. |
| GetObjectData(SerializationInfo, StreamingContext) |
Implements the ISerializable interface and returns the data needed to serialize a HashSet<T> object. |
| IntersectWith(IEnumerable<T>) |
Modifies the current HashSet<T> object to contain only elements that are present in that object and in the specified collection. |
| IsProperSubsetOf(IEnumerable<T>) |
Determines whether a HashSet<T> object is a proper subset of the specified collection. |
| IsProperSupersetOf(IEnumerable<T>) |
Determines whether a HashSet<T> object is a proper superset of the specified collection. |
| IsSubsetOf(IEnumerable<T>) |
Determines whether a HashSet<T> object is a subset of the specified collection. |
| IsSupersetOf(IEnumerable<T>) |
Determines whether a HashSet<T> object is a superset of the specified collection. |
| OnDeserialization(Object) |
Implements the ISerializable interface and raises the deserialization event when the deserialization is complete. |
| Overlaps(IEnumerable<T>) |
Determines whether the current HashSet<T> object and a specified collection share common elements. |
| Remove(T) |
Removes the specified element from a HashSet<T> object. |
| RemoveWhere(Predicate<T>) |
Removes all elements that match the conditions defined by the specified predicate from a HashSet<T> collection. |
| SetEquals(IEnumerable<T>) |
Determines whether a HashSet<T> object and the specified collection contain the same elements. |
| SymmetricExceptWith(IEnumerable<T>) |
Modifies the current HashSet<T> object to contain only elements that are present either in that object or in the specified collection, but not both. |
| TrimExcess() |
Sets the capacity of a HashSet<T> object to the actual number of elements it contains, rounded up to a nearby, implementation-specific value. |
| TryGetValue(T, T) | |
| UnionWith(IEnumerable<T>) |
Modifies the current HashSet<T> object to contain all elements that are present in itself, the specified collection, or both. |
Explicit Interface Implementations
| ICollection<T>.Add(T) |
Adds an item to an ICollection<T> object. |
| ICollection<T>.IsReadOnly |
Gets a value indicating whether a collection is read-only. |
| IEnumerable<T>.GetEnumerator() |
Returns an enumerator that iterates through a collection. |
| IEnumerable.GetEnumerator() |
Returns an enumerator that iterates through a collection. |