Search code examples
c#.netimmutabilitylookupreadonly-collection

Difference between ReadOnlyDictionary and Lookup in .Net


I'm still learning much about immutability and when to use such objects and have started incorporating more Lookups into my coding for the fact that I knew them to be immutable and, hence, often better to use than Dictionaries that could be changed by clients.

That being said, I know there has been a good deal of work on introducing ReadOnlyDictionaries into .Net and I'm a bit confused where each would be more useful than the other and what specifically makes them different. I've looked online, but can't seem to find any articles explaining this difference.

For example, I saw this question and figured a Lookup would be a more ideal solution, but am confused as to why it wouldn't be.

Can anyone point me in the right direction / explain where either would be used over the other.

Thanks!!


Solution

  • Lookups are an easy way to group collections, where you could have one or more values for a given key. A Dictionary gives you one value for a give key, and one value only. Depending on your scenario, it may make most sense to have a Dictionary where you get back one value, or you may want to have a Lookup which would give you a collection of values.

    Without a Lookup if you wanted a collection of values for a certain key you'd be stuck with something ugly like

    Dictionary<int, IEnumerable<String>>
    

    Yuk. See https://msdn.microsoft.com/en-us/library/bb460184%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 for more on Lookups.