保留顺序的 HashSet
我需要一个保留插入顺序的 HashSet,框架中是否有任何实现?
I need a HashSet that preserves insertion ordering, are there any implementations of this in the framework?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 OrderedDictionary 保留插入顺序。但要注意移除物品的成本 (O(n))。
You can use OrderedDictionary to preserve the order of insertion. But beware of the cost of Removing items (O(n)).
标准 .NET
HashSet
不保留插入顺序。对于简单的测试,插入顺序可能会由于意外而被保留,但不能保证并且并不总是这样。证明中间做一些删除就足够了。
有关详细信息,请参阅此问题:HashSet 保留插入顺序吗?
我已经简单地实现了一个保证插入顺序的
HashSet
。它使用Dictionary
来查找项目,并使用LinkedList
来保持顺序。所有三个插入、删除和查找工作仍然是 O(1)。Standard .NET
HashSet
do not preserve the insertion order.For simple tests the insertion order may be preserved due to an accident, but it's not guaranteed and would not always work that way. To prove that it is enough to do some removals in between.
See this question for more information on that: Does HashSet preserve insertion order?
I have briefly implemented a
HashSet
which guarantees insertion order. It uses theDictionary
to look up items and theLinkedList
to preserve order. All three insertion, removal and lookup work still in O(1).您可以使用
KeyedCollection< 轻松获得此功能TKey,TItem>
为 TKey 和 TItem 指定相同的类型参数:You can get this functionality easily using
KeyedCollection<TKey,TItem>
specifying the same type argument for TKey and TItem:如果您需要
Add
、Remove
、Contains
和顺序保留的恒定复杂性,那么.NET Framework 4.5中没有这样的集合。如果您同意第 3 方代码,请查看我的存储库(宽松的 MIT 许可证):
https://github.com/OndrejPetrzilka/Rock.Collections
有
OrderedHashSet;
集合:HashSet
源代码(来自 .NET Core)HashSet
Add
和Remove
具有相同的操作复杂性与HashSet
相比,操作速度慢 20%,If you need constant complexity of
Add
,Remove
,Contains
and order preservation, then there's no such collection in .NET Framework 4.5.If you're okay with 3rd party code, take a look at my repository (permissive MIT license):
https://github.com/OndrejPetrzilka/Rock.Collections
There's
OrderedHashSet<T>
collection:HashSet<T>
source code (from .NET Core)HashSet<T>
Add
andRemove
operations are 20% slower compared toHashSet<T>