何时使用HashTable

amm*_*med 25 c#

在C#中我发现自己使用一个List<T>,IList<T>IEnumerable<T>的99%的时间.是否有一种情况,使用a HashTable(或Dictionary<T,T>2.0及以上)比这些更好?

编辑:

正如所指出的那样,有人想对这个集合做什么通常会决定一个人应该使用什么,所以你何时会使用Hashtable/ Dictonary<T,T>over List<T>

Dav*_*001 19

也许与OPs问题没有直接关系,但是有一篇关于在哪个集合结构中使用的有用博客文章:SortedSets

Basically, what you want to do with the collection determines what type of collection you should create.

To summarise in more detail:

  • Use IList if you want to be able to enumerate and/or modify the collection (normally adding at end of list)
  • Use IEnumeration if you just want to enumerate the collection (don't need to add/remove - usually used as a return type)
  • Use IDictionary if you want to access elements by a key (adding/removing elements quickly using a key)
  • Use SortedSet if you want to access a collection in a predefined order (most common usage being to access the collection in order)

  • Overall, use Dictionary if you want to access/modify items by key in no particular order (preferred over list as that's generally done in order, preferred over enumeration as you can't modify an enumeration, preferred over hashtable as that's not strictly typed, preferred over sortedlist when you don't need keys sorted)


kem*_*002 9

当您希望基于键快速查找项目时,可以使用哈希表(字典).

如果你通常使用List, IList or IEnumerable这意味着你正在循环数据(在IEnumerable的情况下,它肯定意味着),并且散列表不会为你提供任何东西.现在,如果您在一个列表中查找值并使用它来访问另一个列表中的数据,那就会有所不同.例如:

  1. 在Item foo列表中查找位置.
  2. foo列表中的位置对应于包含Foo_Value的另一个列表中的位置.
  3. 访问位置以秒为单位列表以获取Foo_Value.

这是一个描述不同数据类型的链接.

另一个环节.


Luk*_*keH 8

hashtable当您需要能够(快速)按键查找项目时,请使用a .

当然,你可以通过搜索IListIEnumerable等的匹配键但这需要O(n)的时间,而不是O(1)HashtableDictionary.