HashSet<T> Конструкторы

Определение

Инициализирует новый экземпляр класса HashSet<T>.

Перегрузки

HashSet<T>()

Инициализирует пустой экземпляр класса HashSet<T>, который использует функцию сравнения по умолчанию для типа набора.

HashSet<T>(IEnumerable<T>)

Инициализирует новый экземпляр класса HashSet<T>, который использует функцию сравнения по умолчанию для типа набора, содержит элементы, скопированные из указанной коллекции, и обладает емкостью, достаточной для того, чтобы вместить количество скопированных элементов.

HashSet<T>(IEqualityComparer<T>)

Инициализирует пустой экземпляр класса HashSet<T>, который использует указанную функцию сравнения для типа набора.

HashSet<T>(Int32)

Инициализирует пустой экземпляр класса HashSet<T>, но резервирует пространство для элементов capacity и использует функцию сравнения по умолчанию для типа набора.

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

Инициализирует новый экземпляр класса HashSet<T>, который использует заданную функцию сравнения для типа набора, содержит элементы, скопированные из указанной коллекции, и обладает емкостью, достаточной для того, чтобы вместить количество скопированных элементов.

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

Инициализирует новый экземпляр класса HashSet<T>, который использует заданную функцию сравнения для типа набора и обладает достаточной емкостью для размещения элементов capacity.

HashSet<T>(SerializationInfo, StreamingContext)
Устаревшие..

Инициализирует новый экземпляр класса HashSet<T> с сериализованными данными.

HashSet<T>()

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Инициализирует пустой экземпляр класса HashSet<T>, который использует функцию сравнения по умолчанию для типа набора.

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

Примеры

В следующем примере показано, как создать и заполнить два HashSet<T> объекта. Этот пример является частью более крупного примера, предоставленного UnionWith для метода .

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

Комментарии

Емкость HashSet<T> объекта — это количество элементов, которые может содержать объект. HashSet<T> Емкость объекта автоматически увеличивается по мере добавления элементов в объект .

Этот конструктор является операцией O(1).

Применяется к

HashSet<T>(IEnumerable<T>)

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Инициализирует новый экземпляр класса HashSet<T>, который использует функцию сравнения по умолчанию для типа набора, содержит элементы, скопированные из указанной коллекции, и обладает емкостью, достаточной для того, чтобы вместить количество скопированных элементов.

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

Параметры

collection
IEnumerable<T>

Коллекция, элементы которой копируются в новый набор.

Исключения

collection имеет значение null.

Примеры

В следующем примере показано, как создать коллекцию HashSet<T> из существующего набора. В этом примере создаются два набора с четными и нечетными целыми числами соответственно. Затем создается третий HashSet<T> объект из четного целочисленного набора.

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> collection)
{
    Console.Write("{");
    foreach (int i in collection)
    {
        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 }
*/
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

Комментарии

Емкость HashSet<T> объекта — это количество элементов, которые может содержать объект. HashSet<T> Емкость объекта автоматически увеличивается по мере добавления элементов в объект .

Если collection содержит дубликаты, набор будет содержать один из каждого уникального элемента. Исключение не будет создано. Таким образом, размер результирующего набора не идентичен размеру collection.

Этот конструктор является операцией O(n), где n — количество элементов в параметре collection .

Применяется к

HashSet<T>(IEqualityComparer<T>)

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Инициализирует пустой экземпляр класса HashSet<T>, который использует указанную функцию сравнения для типа набора.

public:
 HashSet(System::Collections::Generic::IEqualityComparer<T> ^ comparer);
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))

Параметры

comparer
IEqualityComparer<T>

Реализация IEqualityComparer<T>, которую следует использовать при сравнении значений в наборе, или значение null, чтобы использовать реализацию EqualityComparer<T> по умолчанию для типа набора.

Комментарии

Емкость HashSet<T> объекта — это количество элементов, которые может содержать объект. HashSet<T> Емкость объекта автоматически увеличивается по мере добавления элементов в объект .

Этот конструктор является операцией O(1).

Применяется к

HashSet<T>(Int32)

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Инициализирует пустой экземпляр класса HashSet<T>, но резервирует пространство для элементов capacity и использует функцию сравнения по умолчанию для типа набора.

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)

Параметры

capacity
Int32

Начальный HashSet<T>размер объекта .

Комментарии

Так как изменение размера является относительно ресурсоемким (требует повторного capacityхэширования), это позволяет свести к минимуму необходимость изменения размера, задав начальную емкость на основе значения .

Применяется к

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

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Инициализирует новый экземпляр класса HashSet<T>, который использует заданную функцию сравнения для типа набора, содержит элементы, скопированные из указанной коллекции, и обладает емкостью, достаточной для того, чтобы вместить количество скопированных элементов.

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

Параметры

collection
IEnumerable<T>

Коллекция, элементы которой копируются в новый набор.

comparer
IEqualityComparer<T>

Реализация IEqualityComparer<T>, которую следует использовать при сравнении значений в наборе, или значение null, чтобы использовать реализацию EqualityComparer<T> по умолчанию для типа набора.

Исключения

collection имеет значение null.

Примеры

В следующем примере используется предоставленный IEqualityComparer<T> объект для сравнения без учета регистра HashSet<T> элементов коллекции типов транспортных средств.

#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:" + Environment.NewLine)
        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(Environment.NewLine + "The updated HashSet contains:" + Environment.NewLine)
        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(Environment.NewLine + "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(Environment.NewLine + "The 'All' vehicles set contains 'roCKeTs'")
        End If

        allVehicles.ExceptWith(someVehicles)
        Console.WriteLine(Environment.NewLine + "The excepted HashSet contains:" + Environment.NewLine)
        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(Environment.NewLine + "The super cool vehicles are:" + Environment.NewLine)
        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

Комментарии

Емкость HashSet<T> объекта — это количество элементов, которые может содержать объект. HashSet<T> Емкость объекта автоматически увеличивается по мере добавления элементов в объект .

Если collection содержит дубликаты, набор будет содержать один из каждого уникального элемента. Исключение не будет создано. Таким образом, размер результирующего набора не идентичен размеру collection.

Этот конструктор является операцией O(n), где n — количество элементов в параметре collection .

Применяется к

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

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Инициализирует новый экземпляр класса HashSet<T>, который использует заданную функцию сравнения для типа набора и обладает достаточной емкостью для размещения элементов capacity.

public:
 HashSet(int capacity, System::Collections::Generic::IEqualityComparer<T> ^ comparer);
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))

Параметры

capacity
Int32

Начальный HashSet<T>размер объекта .

comparer
IEqualityComparer<T>

Реализация IEqualityComparer<T>, которую следует использовать при сравнении значений в наборе, или NULL (Nothing в Visual Basic), чтобы использовать реализацию IEqualityComparer<T> по умолчанию для типа набора.

Комментарии

Так как изменение размера является относительно ресурсоемким (требует повторного capacityхэширования), это позволяет свести к минимуму необходимость изменения размера, задав начальную емкость на основе значения .

Применяется к

HashSet<T>(SerializationInfo, StreamingContext)

Исходный код:
HashSet.cs
Исходный код:
HashSet.cs
Исходный код:
HashSet.cs

Внимание!

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

Инициализирует новый экземпляр класса HashSet<T> с сериализованными данными.

protected:
 HashSet(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected HashSet (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
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>
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
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)

Параметры

info
SerializationInfo

Объект SerializationInfo, который содержит сведения, требуемые для сериализации объекта HashSet<T>.

context
StreamingContext

Структура StreamingContext, содержащая исходный и конечный объекты сериализованного потока, связанного с объектом HashSet<T>.

Атрибуты

Комментарии

Этот конструктор вызывается во время десериализации, чтобы воссоздать объект, передаваемый по потоку. Дополнительные сведения см. в разделе Сериализация XML и SOAP.

Применяется к