对于包含 10 个或更少项目的集合,我应该使用字典吗?还是有更好的选择?
我有一个对象列表,我需要尽快找到一个对象(通过它的名称属性)。我应该使用什么数据结构?我知道我可以使用字典,但列表中的项目永远不会超过 10 个,如果我没记错的话,如果集合包含 10 个或更少的项目,字典将实现为数组。
谢谢。
I have a list of objects and I need to find an object as quickly as possible (by it's name property). What data-structure should I use? I know I can use a Dictionary, but there wont ever be more than 10 items in the list, and if I remember correctly the dictionary is implemented as an array if the collection contains 10 items or less.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
MSDN 建议对包含 10 个项目的集合使用 ListDictionary或更少:
MSDN recommends the ListDictionary for collections with 10 items or less:
如果您确定项目少于 10 个,您可能需要考虑 System.Collections.Specialized.ListDictionary。
还要考虑 System.Collections.Specialized.HybridDictionary ,它会在大小增加到阈值以上时切换行为(开销很小),如果您的假设错误,这会很方便。
You may want to consider the
System.Collections.Specialized.ListDictionary
if you are certain there will be less than ten items.Also consider the
System.Collections.Specialized.HybridDictionary
which switches behaviour (with a small overhead) should the size increase above a threshold, handy if your assumption is wrong.由于您希望通过属性进行尽可能最快的查找,因此您应该使用
Dictionary
。如果您想要快速查找,大小不会对您造成伤害。这并不是说只有 10 项或更少的Dictionary
就占用了大量内存。Dictionary
有一个构造函数,它采用 int 来设置容量。Since you want fastest possible lookup by a property you should use
Dictionary<Key, Value>
. The size doesn't hurt you if you want fast lookup. It's not that aDictionary<Key, Value>
of just 10 items or less is taking up a ton of memory.Dictionary<Key, Value>
has a constructor that takes an int to set the capacity.为什么不直接使用哈希表呢?它位于 System.Collections 命名空间中。
Why not just use a Hashtable? It's in the System.Collections namespace.
对于您的情况,
KeyedCollection
就可以了。它是一个混合结构,构造函数采用一个参数来表示结构应从线性列表切换到基于哈希的查找。是的,它是通用的。一个缺点是它是一个抽象类,因此您必须自己派生一个。
那么你可以这样称呼它:
For your case,
KeyedCollection<TKey, TItem>
will do. It is a hybrid structure, the constructor takes a parameter to denote from what size onward the structure should switch from linear list to a hash based lookup. And yes it is generic.One downside is it is an abstract class, so you will have to derive one yourself.
Then you could call it: