HashSet<T> 类

定义

表示值的集。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)

类型参数

T

哈希集中的元素类型。The type of elements in the hash set.

继承
HashSet<T>
属性
实现

示例

下面的示例演示如何合并两个不同的集。The following example demonstrates how to merge two disparate sets. 此示例将创建两个 @no__t 为0的对象,并分别用偶数和奇数填充它们。This example creates two HashSet<T> objects, and populates them with even and odd numbers, respectively. 第三 @no__t 0 对象是从包含偶数的集创建的。A third HashSet<T> object is created from the set that contains the even numbers. 然后,该示例调用 UnionWith 方法,这会将奇数设置为第三个集。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);

        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 }

注解

@No__t 0 类提供高性能设置操作。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.

备注

@no__t 从 .NET Framework 4.6.NET Framework 4.6 开始实现 @no__t 1 接口;在 .NET Framework 的以前版本中,@no__t 类未实现此接口。HashSet<T> implements the IReadOnlyCollection<T> interface starting with the .NET Framework 4.6.NET Framework 4.6; in previous versions of the .NET Framework, the HashSet<T> class did not implement this interface.

@No__t 的容量是指对象可以容纳的元素数。The capacity of a HashSet<T> object is the number of elements that the object can hold. 当向对象添加元素时,@no__t 0 对象的容量会自动增加。A HashSet<T> object's capacity automatically increases as elements are added to the object.

@No__t-0 类基于数学集的模型,并提供高性能集操作,类似于访问 @no__t 或 @no__t 集合的键。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. 简单而言,可以将 HashSet<T> 类视为没有值的 @no__t 1 集合。In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey,TValue> collection without values.

@No__t 0 集合未排序且不能包含重复元素。A HashSet<T> collection is not sorted and cannot contain duplicate elements. 如果顺序或元素复制比应用程序的性能更重要,请考虑将 List<T> 类与 @no__t 方法一起使用。If order or element duplication is more important than performance for your application, consider using the List<T> class together with the Sort method.

@no__t 提供了许多数学集操作,如 set 加法(union)和 set 减法。HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction. 下表列出了提供的 @no__t 0 操作及其数学等效项。The following table lists the provided HashSet<T> operations and their mathematical equivalents.

HashSet 操作HashSet operation 数学等效项Mathematical equivalent
UnionWith Union 或 set 加法Union or set addition
IntersectWith 交集Intersection
ExceptWith 设置减法Set subtraction
SymmetricExceptWith 对称差异Symmetric difference

除了列出的 set 操作以外,@no__t 的类还提供了一些方法,用于确定设置的相等性、重叠集以及集是另一个集的子集还是超集。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: 对于非常大的 @no__t 0 对象,可以通过在运行时环境中将@no__t 3配置元素的 @no__t 属性设置为 true,将64位系统上的最大容量增加到2000000000个元素。.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.

.NET Framework 4.NET Framework 4 开始,@no__t 类实现第 2 @no__t 接口。Starting with the .NET Framework 4.NET Framework 4, the HashSet<T> class implements the ISet<T> interface.

HashSet 和 LINQ Set 运算HashSet and LINQ Set Operations

LINQ 为实现 @no__t 或 @no__t 接口的任何数据源提供对 DistinctUnion、@no__t 和 @no__t 集操作的访问。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> 提供了一个更大、更可靠的集合操作集合。HashSet<T> provides a larger and more robust collection of set operations. 例如,HashSet<T> 提供 IsSubsetOfIsSupersetOf 等比较。For example, HashSet<T> provides comparisons such as IsSubsetOf and IsSupersetOf.

LINQ set 操作与 @no__t 0 操作之间的主要区别在于,LINQ set 操作始终返回新的 @no__t 1 集合,而 @no__t 2 等效方法修改当前集合。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.

通常情况下,如果您必须创建新集,或者您的应用程序只需要访问所提供的 set 操作,则对任何 @no__t 0 的集合或数组使用 LINQ set 操作即可。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. 但是,如果你的应用程序需要访问其他设置操作,或者如果不需要或不需要创建新集合,请使用 HashSet<T> 类。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.

下表显示 HashSet<T> 操作及其等效的 LINQ set 操作。The following table shows the HashSet<T> operations and their equivalent LINQ set operations.

HashSet 操作HashSet operation LINQ 等效项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.

构造函数

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> 类的一个新实例,该实例使用集类型的默认相等比较器,包含从指定的集合复制的元素,并且有足够的容量容纳所复制的这些元素。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>)

初始化 HashSet<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>)

初始化 HashSet<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> 类的一个新实例,该实例为空,但已为 capacity 项保留空间并使用集类型的默认相等比较器。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>)

初始化 HashSet<T> 类的新实例,该实例使用集类型的指定相等比较器,并且其容量足以容纳 capacity 元素。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> 类的新实例。Initializes a new instance of the HashSet<T> class with serialized data.

属性

Comparer

获取用于确定集中的值是否相等的 IEqualityComparer<T> 对象。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.

方法

Add(T)

将指定的元素添加到集中。Adds the specified element to a set.

Clear()

HashSet<T> 对象中移除所有元素。Removes all elements from a HashSet<T> object.

Contains(T)

确定 HashSet<T> 对象是否包含指定的元素。Determines whether a HashSet<T> object contains the specified element.

CopyTo(T[])

HashSet<T> 对象的元素复制到数组中。Copies the elements of a HashSet<T> object to an array.

CopyTo(T[], Int32)

从指定数组索引处开始,将 HashSet<T> 对象的元素复制到数组中。Copies the elements of a HashSet<T> object to an array, starting at the specified array index.

CopyTo(T[], Int32, Int32)

从指定数组索引处开始,将 HashSet<T> 对象的指定数目的元素复制到数组中。Copies the specified number of elements of a HashSet<T> object to an array, starting at the specified array index.

CreateSetComparer()

返回 IEqualityComparer 对象,该对象可用于对 HashSet<T> 对象进行相等测试。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.

(继承自 Object)
ExceptWith(IEnumerable<T>)

从当前 HashSet<T> 对象中移除指定集合中的所有元素。Removes all elements in the specified collection from the current HashSet<T> object.

GetEnumerator()

返回循环访问 HashSet<T> 对象的枚举器。Returns an enumerator that iterates through a HashSet<T> object.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

实现 ISerializable 接口并返回序列化 HashSet<T> 对象所需的数据。Implements the ISerializable interface and returns the data needed to serialize a HashSet<T> object.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
IntersectWith(IEnumerable<T>)

修改当前的 HashSet<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>)

确定 HashSet<T> 对象是否为指定集合的真子集。Determines whether a HashSet<T> object is a proper subset of the specified collection.

IsProperSupersetOf(IEnumerable<T>)

确定 HashSet<T> 对象是否为指定集合的真超集。Determines whether a HashSet<T> object is a proper superset of the specified collection.

IsSubsetOf(IEnumerable<T>)

确定 HashSet<T> 对象是否为指定集合的子集。Determines whether a HashSet<T> object is a subset of the specified collection.

IsSupersetOf(IEnumerable<T>)

确定 HashSet<T> 对象是否为指定集合的超集。Determines whether a HashSet<T> object is a superset of the specified collection.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OnDeserialization(Object)

实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Overlaps(IEnumerable<T>)

确定当前的 HashSet<T> 对象和指定的集合是否共享常见元素。Determines whether the current HashSet<T> object and a specified collection share common elements.

Remove(T)

HashSet<T> 对象中移除指定的元素。Removes the specified element from a HashSet<T> object.

RemoveWhere(Predicate<T>)

HashSet<T> 集合中移除与指定的谓词所定义的条件相匹配的所有元素。Removes all elements that match the conditions defined by the specified predicate from a HashSet<T> collection.

SetEquals(IEnumerable<T>)

确定是否 HashSet<T> 对象和指定集合包含相同的元素。Determines whether a HashSet<T> object and the specified collection contain the same elements.

SymmetricExceptWith(IEnumerable<T>)

修改当前 HashSet<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()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
TrimExcess()

HashSet<T> 对象的容量设置为它包含的实际元素数,向上舍入为接近的特定于实现的值。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>)

修改当前 HashSet<T> 对象以包含存在于该对象中、指定集合中或两者中的所有元素。Modifies the current HashSet<T> object to contain all elements that are present in itself, the specified collection, or both.

显式界面实现

ICollection<T>.Add(T)

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

扩展方法

CopyToDataTable<T>(IEnumerable<T>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 IEnumerable<T> 对象副本的 DataRowReturns 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts 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. 集合中仅包括具有匹配 XName 的元素。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. 集合中仅包括具有匹配 XName 的元素。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. 集合中仅包括具有匹配 XName 的元素。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.

适用于

另请参阅