HashSet<T> HashSet<T> HashSet<T> HashSet<T> Constructors

Definition

Overloads

HashSet<T>() HashSet<T>() 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>) HashSet<T>(IEnumerable<T>) HashSet<T>(IEnumerable<T>) 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>) HashSet<T>(IEqualityComparer<T>) HashSet<T>(IEqualityComparer<T>) 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>(Int32) HashSet<T>(Int32) 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>(IEnumerable<T>, IEqualityComparer<T>) HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) 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>(Int32, IEqualityComparer<T>) HashSet<T>(Int32, IEqualityComparer<T>) 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) HashSet<T>(SerializationInfo, StreamingContext) HashSet<T>(SerializationInfo, StreamingContext) HashSet<T>(SerializationInfo, StreamingContext)

Initializes a new instance of the HashSet<T> class with serialized data.

HashSet<T>() HashSet<T>() HashSet<T>()

Initializes a new instance of the HashSet<T> class that is empty and uses the default equality comparer for the set type.

public:
 HashSet();
public HashSet ();
Public Sub New ()

Examples

The following example demonstrates how to create and populate two HashSet<T> objects. This example is part of a larger example provided for the UnionWith method.

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

Remarks

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.

This constructor is an O(1) operation.

HashSet<T>(IEnumerable<T>) HashSet<T>(IEnumerable<T>) HashSet<T>(IEnumerable<T>) 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.

public:
 HashSet(System::Collections::Generic::IEnumerable<T> ^ collection);
public HashSet (System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.HashSet<'T> : seq<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (collection As IEnumerable(Of T))

Parameters

collection
IEnumerable<T> IEnumerable<T> IEnumerable<T> IEnumerable<T>

The collection whose elements are copied to the new set.

Exceptions

Examples

The following example shows how to create a HashSet<T> collection from an existing set. In this example, two sets are created with even and odd integers, respectively. A third HashSet<T> object is then created from the even integer set.

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

Remarks

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.

If collection contains duplicates, the set will contain one of each unique element. No exception will be thrown. Therefore, the size of the resulting set is not identical to the size of collection.

This constructor is an O(n) operation, where n is the number of elements in the collection parameter.

HashSet<T>(IEqualityComparer<T>) HashSet<T>(IEqualityComparer<T>) HashSet<T>(IEqualityComparer<T>) 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.

public:
 HashSet(System::Collections::Generic::IEqualityComparer<T> ^ comparer);
public HashSet (System.Collections.Generic.IEqualityComparer<T> comparer);
new System.Collections.Generic.HashSet<'T> : System.Collections.Generic.IEqualityComparer<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (comparer As IEqualityComparer(Of T))

Parameters

comparer
IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T>

The IEqualityComparer<T> implementation to use when comparing values in the set, or null to use the default EqualityComparer<T> implementation for the set type.

Remarks

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.

This constructor is an O(1) operation.

HashSet<T>(Int32) HashSet<T>(Int32) HashSet<T>(Int32) 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.

public:
 HashSet(int capacity);
public HashSet (int capacity);
new System.Collections.Generic.HashSet<'T> : int -> System.Collections.Generic.HashSet<'T>
Public Sub New (capacity As Integer)

Parameters

capacity
Int32 Int32 Int32 Int32

The initial size of the HashSet<T>

Remarks

Since resizes are relatively expensive (require rehashing), this attempts to minimize the need to resize by setting the initial capacity based on the value of the capacity.

HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) HashSet<T>(IEnumerable<T>, IEqualityComparer<T>) 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.

public:
 HashSet(System::Collections::Generic::IEnumerable<T> ^ collection, System::Collections::Generic::IEqualityComparer<T> ^ comparer);
public HashSet (System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer);
new System.Collections.Generic.HashSet<'T> : seq<'T> * System.Collections.Generic.IEqualityComparer<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (collection As IEnumerable(Of T), comparer As IEqualityComparer(Of T))

Parameters

collection
IEnumerable<T> IEnumerable<T> IEnumerable<T> IEnumerable<T>

The collection whose elements are copied to the new set.

comparer
IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T>

The IEqualityComparer<T> implementation to use when comparing values in the set, or null to use the default EqualityComparer<T> implementation for the set type.

Exceptions

Examples

The following example uses a supplied IEqualityComparer<T> to allow case-insensitive comparisons on the elements of a HashSet<T> collection of vehicle types.

#using <System.Core.dll>

using namespace System;
using namespace System::Collections::Generic;

ref class Program
{
public:
    static void Main()
    {
        HashSet<String^> ^allVehicles = gcnew HashSet<String^>(StringComparer::OrdinalIgnoreCase);
        List<String^>^ someVehicles = gcnew List<String^>();

        someVehicles->Add("Planes");
        someVehicles->Add("Trains");
        someVehicles->Add("Automobiles");

        // Add in the vehicles contained in the someVehicles list.
        allVehicles->UnionWith(someVehicles);

        Console::WriteLine("The current HashSet contains:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }

        allVehicles->Add("Ships");
        allVehicles->Add("Motorcycles");
        allVehicles->Add("Rockets");
        allVehicles->Add("Helicopters");
        allVehicles->Add("Submarines");

        Console::WriteLine("\nThe updated HashSet contains:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }

        // Verify that the 'All Vehicles' set contains at least the vehicles in
        // the 'Some Vehicles' list.
        if (allVehicles->IsSupersetOf(someVehicles))
        {
            Console::Write("\nThe 'All' vehicles set contains everything in ");
            Console::WriteLine("'Some' vechicles list.");
        }

        // Check for Rockets. Here the OrdinalIgnoreCase comparer will compare
        // true for the mixed-case vehicle type.
        if (allVehicles->Contains("roCKeTs"))
        {
            Console::WriteLine("\nThe 'All' vehicles set contains 'roCKeTs'");
        }

        allVehicles->ExceptWith(someVehicles);
        Console::WriteLine("\nThe excepted HashSet contains:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }

        // Remove all the vehicles that are not 'super cool'.
        allVehicles->RemoveWhere(gcnew Predicate<String^>(&isNotSuperCool));

        Console::WriteLine("\nThe super cool vehicles are:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }
    }

private:
    // Predicate to determine vehicle 'coolness'.
    static bool isNotSuperCool(String^ vehicle)
    {
        bool superCool = (vehicle == "Helicopters") || (vehicle == "Motorcycles");

        return !superCool;
    }
};

int main()
{
    Program::Main();
}

// The program writes the following output to the console::
//
// The current HashSet contains:
//
// Planes
// Trains
// Automobiles
//
// The updated HashSet contains:
//
// Planes
// Trains
// Automobiles
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The 'All' vehicles set contains everything in 'Some' vechicles list.
//
// The 'All' vehicles set contains 'roCKeTs'
//
// The excepted HashSet contains:
//
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The super cool vehicles are:
//
// Motorcycles
// Helicopters
HashSet<string> allVehicles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<string> someVehicles = new List<string>();

someVehicles.Add("Planes");
someVehicles.Add("Trains");
someVehicles.Add("Automobiles");

// Add in the vehicles contained in the someVehicles list.
allVehicles.UnionWith(someVehicles);

Console.WriteLine("The current HashSet contains:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

allVehicles.Add("Ships");
allVehicles.Add("Motorcycles");
allVehicles.Add("Rockets");
allVehicles.Add("Helicopters");
allVehicles.Add("Submarines");

Console.WriteLine("\nThe updated HashSet contains:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

// Verify that the 'All Vehicles' set contains at least the vehicles in
// the 'Some Vehicles' list.
if (allVehicles.IsSupersetOf(someVehicles))
{
    Console.Write("\nThe 'All' vehicles set contains everything in ");
    Console.WriteLine("'Some' vechicles list.");
}

// Check for Rockets. Here the OrdinalIgnoreCase comparer will compare
// true for the mixed-case vehicle type.
if (allVehicles.Contains("roCKeTs"))
{
    Console.WriteLine("\nThe 'All' vehicles set contains 'roCKeTs'");
}

allVehicles.ExceptWith(someVehicles);
Console.WriteLine("\nThe excepted HashSet contains:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

// Remove all the vehicles that are not 'super cool'.
allVehicles.RemoveWhere(isNotSuperCool);

Console.WriteLine("\nThe super cool vehicles are:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

// Predicate to determine vehicle 'coolness'.
bool isNotSuperCool(string vehicle)
{
    bool superCool = (vehicle == "Helicopters") || (vehicle == "Motorcycles");

    return !superCool;
}

// The program writes the following output to the console.
//
// The current HashSet contains:
//
// Planes
// Trains
// Automobiles
//
// The updated HashSet contains:
//
// Planes
// Trains
// Automobiles
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The 'All' vehicles set contains everything in 'Some' vechicles list.
//
// The 'All' vehicles set contains 'roCKeTs'
//
// The excepted HashSet contains:
//
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The super cool vehicles are:
//
// Motorcycles
// Helicopters
Imports System.Collections.Generic

Class Program
    Public Shared Sub Main()
        Dim allVehicles As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
        Dim someVehicles As New List(Of String)()

        someVehicles.Add("Planes")
        someVehicles.Add("Trains")
        someVehicles.Add("Automobiles")

        ' Add in the vehicles contained in the someVehicles list.
        allVehicles.UnionWith(someVehicles)

        Console.WriteLine("The current HashSet contains:" + vbNewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle

        allVehicles.Add("Ships")
        allVehicles.Add("Motorcycles")
        allVehicles.Add("Rockets")
        allVehicles.Add("Helicopters")
        allVehicles.Add("Submarines")

        Console.WriteLine(vbNewLine + "The updated HashSet contains:" + vbNewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle

        ' Verify that the 'All Vehicles' set contains at least the vehicles in
        ' the 'Some Vehicles' list.
        If allVehicles.IsSupersetOf(someVehicles) Then
            Console.Write(vbNewLine + "The 'All' vehicles set contains everything in ")
            Console.WriteLine("'Some' vechicles list.")
        End If

        ' Check for Rockets. Here the OrdinalIgnoreCase comparer will compare
        ' True for the mixed-case vehicle type.
        If allVehicles.Contains("roCKeTs") Then
            Console.WriteLine(vbNewLine + "The 'All' vehicles set contains 'roCKeTs'")
        End If

        allVehicles.ExceptWith(someVehicles)
        Console.WriteLine(vbNewLine + "The excepted HashSet contains:" + vbNewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle

        ' Remove all the vehicles that are not 'super cool'.
        allVehicles.RemoveWhere(AddressOf isNotSuperCool)

        Console.WriteLine(vbNewLine + "The super cool vehicles are:" + vbNewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle
    End Sub

    ' Predicate to determine vehicle 'coolness'.
    Private Shared Function isNotSuperCool(vehicle As String) As Boolean
        Dim notSuperCool As Boolean = _
            (vehicle <> "Helicopters") And (vehicle <> "Motorcycles")

        Return notSuperCool
    End Function
End Class

'
' The program writes the following output to the console.
'
' The current HashSet contains:
'
' Planes
' Trains
' Automobiles
'
' The updated HashSet contains:
'
' Planes
' Trains
' Automobiles
' Ships
' Motorcycles
' Rockets
' Helicopters
' Submarines
'
' The 'All' vehicles set contains everything in 'Some' vechicles list.
'
' The 'All' vehicles set contains 'roCKeTs'
'
' The excepted HashSet contains:
'
' Ships
' Motorcycles
' Rockets
' Helicopters
' Submarines
'
' The super cool vehicles are:
'
' Motorcycles
' Helicopters

Remarks

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.

If collection contains duplicates, the set will contain one of each unique element. No exception will be thrown. Therefore, the size of the resulting set is not identical to the size of collection.

This constructor is an O(n) operation, where n is the number of elements in the collection parameter.

HashSet<T>(Int32, IEqualityComparer<T>) HashSet<T>(Int32, IEqualityComparer<T>) HashSet<T>(Int32, IEqualityComparer<T>) 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.

public:
 HashSet(int capacity, System::Collections::Generic::IEqualityComparer<T> ^ comparer);
public HashSet (int capacity, System.Collections.Generic.IEqualityComparer<T> comparer);
new System.Collections.Generic.HashSet<'T> : int * System.Collections.Generic.IEqualityComparer<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of T))

Parameters

capacity
Int32 Int32 Int32 Int32

The initial size of the HashSet<T>

comparer
IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T>

The IEqualityComparer<T> implementation to use when comparing values in the set, or null (Nothing in Visual Basic) to use the default IEqualityComparer<T> implementation for the set type.

Remarks

Since resizes are relatively expensive (require rehashing), this attempts to minimize the need to resize by setting the initial capacity based on the value of the capacity.

HashSet<T>(SerializationInfo, StreamingContext) HashSet<T>(SerializationInfo, StreamingContext) HashSet<T>(SerializationInfo, StreamingContext) HashSet<T>(SerializationInfo, StreamingContext)

Initializes a new instance of the HashSet<T> class with serialized data.

protected:
 HashSet(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected HashSet (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Generic.HashSet<'T> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.HashSet<'T>
Protected Sub New (info As SerializationInfo, context As StreamingContext)

Parameters

info
SerializationInfo SerializationInfo SerializationInfo SerializationInfo

A SerializationInfo object that contains the information required to serialize the HashSet<T> object.

context
StreamingContext StreamingContext StreamingContext StreamingContext

A StreamingContext structure that contains the source and destination of the serialized stream associated with the HashSet<T> object.

Remarks

This constructor is called during deserialization to reconstitute an object that is transmitted over a stream. For more information, see XML and SOAP Serialization.

Applies to