HashSet c# HashSet数据结构在. net Framework 3.5中引入。实现成员的完整列表可以在HashSet MSDN页面上找到。

在哪里使用? 你为什么要用它?


当前回答

A HashSet holds a set of objects, but in a way that allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference. Take a look here There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.

c#中的HashSet类采用第一种方法,因此不保留元素的顺序。它比常规List快得多。一些基本的基准测试表明,HashSet在处理主要类型(int、double、bool等)时要快得多。在处理类对象时速度要快得多。关键是HashSet很快。

HashSet的唯一问题是不能通过索引进行访问。要访问元素,您可以使用枚举数或使用内置函数将HashSet转换为List并遍历它。看这里

其他回答

A HashSet holds a set of objects, but in a way that allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference. Take a look here There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.

c#中的HashSet类采用第一种方法,因此不保留元素的顺序。它比常规List快得多。一些基本的基准测试表明,HashSet在处理主要类型(int、double、bool等)时要快得多。在处理类对象时速度要快得多。关键是HashSet很快。

HashSet的唯一问题是不能通过索引进行访问。要访问元素,您可以使用枚举数或使用内置函数将HashSet转换为List并遍历它。看这里

HashSet有一个内部结构(hash),可以在其中快速搜索和识别项目。缺点是遍历HashSet(或按索引获取项)相当慢。

那么为什么有人想知道一个条目是否已经存在于一个集合中呢?

HashSet有用的一种情况是从可能存在重复值的列表中获取不同的值。一旦将项添加到HashSet中,就可以快速确定该项是否存在(包含操作符)。

HashSet的其他优点是集合操作:IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith。

如果您熟悉对象约束语言,那么您将识别这些set操作。您还将看到它离可执行UML的实现更近了一步。

从应用程序的角度来看,如果只需要避免重复,那么HashSet就是你要找的,因为它的查找、插入和删除复杂度是O(1)常量。这意味着,不管HashSet有多少个元素,检查是否有这样的元素都需要相同的时间,加上由于您在O(1)处插入元素,因此它非常适合这种情况。

简单地说,没有透露厨房的秘密: 一般来说,集合是不包含重复元素的集合,其元素没有特定的顺序。因此,HashSet<T>类似于泛型List<T>,但是为了快速查找(通过哈希表,顾名思义)而进行了优化,代价是失去顺序。