Lookup() 和 Dictionary(Of list()) 的区别 [英] Difference between Lookup() and Dictionary(Of list())
问题描述
我正在努力思考哪些数据结构最有效,以及何时/何地使用哪些数据结构.
I'm trying to wrap my head around which data structures are the most efficient and when / where to use which ones.
现在,可能是我只是不太了解这些结构,但是 ILookup(of key, ...)
与 Dictionary(of键,列表(...))
?
Now, it could be that I simply just don't understand the structures well enough, but how is an ILookup(of key, ...)
different from a Dictionary(of key, list(of ...))
?
还有我想在哪里使用 ILookup
以及在程序速度/内存/数据访问等方面更有效的地方?
Also where would I want to use an ILookup
and where would it be more efficient in terms of program speed / memory / data accessing, etc?
推荐答案
两个显着差异:
Lookup
是不可变的.是的 :) (至少,我相信具体的Lookup
类是不可变的,并且ILookup
接口不提供任何可变成员.可以> 当然是其他可变实现.)- 当您查找在查找中不存在的键时,您会得到一个空序列而不是
KeyNotFoundException
.(因此没有TryGetValue
,AFAICR.)
Lookup
is immutable. Yay :) (At least, I believe the concreteLookup
class is immutable, and theILookup
interface doesn't provide any mutating members. There could be other mutable implementations, of course.)- When you lookup a key which isn't present in a lookup, you get an empty sequence back instead of a
KeyNotFoundException
. (Hence there's noTryGetValue
, AFAICR.)
它们可能在效率上是相同的——例如,查找很可能在幕后使用 Dictionary
.根据您的要求在它们之间进行选择.就个人而言,我发现查找通常比 Dictionary
更适合,主要是由于上面的前两点.
They're likely to be equivalent in efficiency - the lookup may well use a Dictionary<TKey, GroupingImplementation<TValue>>
behind the scenes, for example. Choose between them based on your requirements. Personally I find that the lookup is usually a better fit than a Dictionary<TKey, List<TValue>>
, mostly due to the first two points above.
注意,作为一个实现细节,用于值的IGrouping<,>
的具体实现实现了IList
,这意味着它是高效的与 Count()
、ElementAt()
等一起使用
Note that as an implementation detail, the concrete implementation of IGrouping<,>
which is used for the values implements IList<TValue>
, which means that it's efficient to use with Count()
, ElementAt()
etc.
这篇关于Lookup() 和 Dictionary(Of list()) 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!