Difference between Lookup() and Dictionary(Of list())
Two significant differences:
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.)
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.
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.
Interesting that nobody has stated the actual biggest difference (Taken directly from MSDN):
A Lookup resembles a Dictionary. The difference is that a Dictionary maps keys to single values, whereas a Lookup maps keys to collections of values.
Both a Dictionary<Key, List<Value>>
and a Lookup<Key, Value>
logically can hold data organized in a similar way and both are of the same order of efficiency. The main difference is a Lookup
is immutable: it has no Add()
methods and no public constructor (and as Jon mentioned you can query a non-existent key without an exception and have the key as part of the grouping).
As to which do you use, it really depends on how you want to use them. If you are maintaining a map of key to multiple values that is constantly being modified, then a Dictionary<Key, List<Value>>
is probably better since it is mutable.
If, however, you have a sequence of data and just want a read-only view of the data organized by key, then a lookup is very easy to construct and will give you a read-only snapshot.