1

What is the best way to store a map of key object to a collection of value objects?
I could use

Dictionary<KeyType, Collection<ValueType>>

but that approach tends to involve a lot of housekeeping, and clutters up the code.

The Lookup type is almost the result I'm looking for, but it's immutable and has no constructor. I could create my own custom class, but it seems like it should exist in the framework somewhere.

Whatsit
  • 10,227
  • 11
  • 42
  • 41

3 Answers3

5

That's about your best answer. It's pretty common to use Dictionary<KeyType, ICollection<ValueType>>. Using the var keyword to declare your local variables is the best way to tidy up.

Other than that, your only option is creating a MultiDictionary<T,K> type. You could also call it Lookup and put it in your own namespace?

Edit: Google says you should take a look at this for an existing implementation: Multi-value Dictionary C# source code (.NET 3.5). BSD2 license means you can use it for commercial apps with at attribution. :)

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
4

You could also, as for tidying, alias the specific generic type:

using MultiDictionary = Dictionary<string, ICollection<int>>;

Then later:

var foo = new MultiDictionary();
Marc
  • 9,254
  • 2
  • 29
  • 31
  • The part I don't like about this is you can't do generic aliases, and it's hard to keep consistency across source files. Fortunately it doesn't break Find All References. – Sam Harwell Aug 06 '09 at 19:26
2

In .NET 3.5, there is ILookup<Tkey,TValue> and Lookup<TKey,TValue> that serves this purpose; however, the default implementation is immutable. I wrote a mutable variant for MiscUtil; EditableLookup<TKey,TValue> - which does exactly what you want.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900