是HashSet< T& gt;与List& T& gt;相同但是具有独特性? [英] Is a HashSet<T> the same as List<T> but with uniqueness?

查看:53
本文介绍了是HashSet< T& gt;与List& T& gt;相同但是具有独特性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要具有在集合中包含唯一项的能力.

I need to have an ability to have unique items in a collection.

我打算使用Dictionary,所以可以使用ContainsKey方法,但是我认为这是浪费,因为我不使用Key/Value对的Value属性.

I was going to use a Dictionary so I could use the ContainsKey method but I thought it would be a waste as I wouldnt use the Value property of the Key/Value pair.

我碰到了 HashSet< T> ,它看起来非常有前途.我只能在 List< T> 文档中找不到的是 HashSet< T> 是无序的.我认为这很好,我认为这意味着未使用 IEqualityComparer 对其进行排序.只要添加项目的顺序在相同的索引位置,我认为就可以了,因为我必须进行重复检查,因此必须对哈希集进行检查,然后再检查所有条目是否是顺序的.

I came across the HashSet<T> which looks very promising. The only thing I can find that I can't find in the List<T> docs is that HashSet<T> is unordered. I think that is fine, I assume it means its not ordered using a IEqualityComparer. As long as the order in which items are added are in the same index position I think it will be ok as I have to do duplicate checking hence the hashset and then check all entries are sequential.

比较这两种类型我还有其他想念的东西吗?

Is there anything else I have missed comparing the two types?

推荐答案

否,重要的是 HashSet< T> 没有任何排序或索引的概念-列表在概念上具有插槽0...n-1,而集合是只是集合".

No, importantly HashSet<T> doesn't have any concept of ordering or indexing - a list conceptually has slots 0....n-1, whereas a set is "just a set".

我认为很好,我认为这意味着它不是使用IEqualityComparer排序的.

I think that is fine, I assume it means its not ordered using a IEqualityComparer.

无论如何,

IEqualityComparer 都不用于订购-它仅 讨论相等性和哈希码. 或元素比较均未对 HashSet< T> 进行排序(例如, or 插入顺序.

IEqualityComparer isn't used for ordering anyway - it only talks about equality and hash codes. HashSet<T> isn't ordered by either an element comparison (as, say, SortedSet<T> is) or insertion order.

只要添加项目的顺序在相同的索引位置,我认为就可以了.

As long as the order in which items are added are in the same index position I think it will be ok.

没有 索引位置,并且当您遍历 HashSet< T> 时,无法保证您会按添加顺序将它们取回.如果您甚至还不知道如何订购,那么 HashSet< T> 就不是您想要的.

There is no index position, and when you iterate over a HashSet<T> there's no guarantee you'll get them back in the order in which you added them. If you're even thinking about ordering, HashSet<T> isn't what you're after.

然后,所有这些对 Dictionary< TKey,TValue> 也是 正确的-您也不应该对在那里的订购做任何假设.

Then again, all of this is also true of Dictionary<TKey, TValue> - you shouldn't make any assumptions about ordering there, either.

这篇关于是HashSet&lt; T&amp; gt;与List&amp; T&amp; gt;相同但是具有独特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆