HashSet<T> Class

Definition

Represents a set of values.

generic <typename T>
public ref class HashSet : 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
[System.Serializable]
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
type HashSet<'T> = class
    interface ICollection<'T>
    interface ISerializable
    interface IDeserializationCallback
    interface ISet<'T>
    interface IReadOnlyCollection<'T>
    interface seq<'T>
    interface IEnumerable
Public Class HashSet(Of T)
Implements ICollection(Of T), IDeserializationCallback, IEnumerable(Of T), IReadOnlyCollection(Of T), ISerializable, ISet(Of T)

Type Parameters

T

The type of elements in the hash set.

Inheritance
HashSet<T>
Attributes
Implements

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.

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);

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.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

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 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.

.NET Framework only: 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 <gcAllowVeryLargeObjects> 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 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>(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>(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)

Initializes a new instance of the HashSet<T> class that is empty, but has reserved space for capacity items and uses the default equality comparer for the set type.

HashSet<T>(Int32, IEqualityComparer<T>)

Initializes a new instance of the HashSet<T> class that uses the specified equality comparer for the set type, and has sufficient capacity to accommodate capacity elements.

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.

EnsureCapacity(Int32)

Ensures that this hash set can hold the specified number of elements without growing.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from 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.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

Implements the ISerializable interface and returns the data needed to serialize a HashSet<T> object.

GetType()

Gets the Type of the current instance.

(Inherited from 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.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
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.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
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)

Searches the set for a given value and returns the equal value it finds, if any.

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.GetEnumerator()

Returns an enumerator that iterates through a collection.

IEnumerable<T>.GetEnumerator()

Returns an enumerator that iterates through a collection.

Extension Methods

CopyToDataTable<T>(IEnumerable<T>)

Returns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>)

Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName)

Returns a filtered collection of elements that contains the ancestors of every node in the source collection. Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>)

Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>)

Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName)

Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>)

Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName)

Returns a filtered collection of the child elements of every element and document in the source collection. Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>)

Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>)

Removes every node in the source collection from its parent node.

Applies to

See also