tags:

views:

1330

answers:

5

Basically I'd like to make a Dictionary work with duplicate keys without going into custom comparer implementations. There is an idea of:

  Dictionary<key, List<value>>

but it still has some overhead. I wish Dictionary had "AllowDuplicates".

+3  A: 

Not in the Fx < 3.5.. You can implement one, obviously, with a Dictionary of IList objects. But then you have the encapsulation issue/responsibility.

If you're using .NET 3.5, use the Lookup class.

Ryan Emerle
A: 

By definition, a Dictionary contains unique keys. Your example above is effectively a sort of two-dimensional keyed array, a structure I've used many times. Why would you want to have duplicate keys? If you did, how would the Dictionary uniquely address its members?

Dave Swersky
Consider a real-world dictionary listing different meanings for the same word. Multiple entries with a common key. Nothing contradictory about that. Members could be addressed by a lookup returning a collection or Enumerable. C++ has had a multimap for ages. It's not an impossible problem. :)
jalf
+2  A: 

.NET 2.0: PowerCollections contains the OrderedMultiDictionary.

Mitch Wheat
+5  A: 

If you're using .NET 3.5 then Lookup is probably what you're after.

LukeH
It's a pity that such a potentially useful class has a few limitations. Such as no public constructor or ability to add/remove items.
Ray
@Ray, Agree completely. Although I guess that's why it's called Lookup rather than something like MultiDictionary, to hint that it's an immutable lookup of some sort rather than a collection to be manipulated. The OP's suggestion of a Dictionary<key, List<value>> would be much more flexible.
LukeH
A: 

“Why would you want to have duplicate keys? “

It is the sorted part of the collection I am lazy about.

I want to sort by things like voltage, amps or temp in my collection and return the interment identifier value i am storing for this sensor.

I'd like to iterate through the top most and lowest most values of these sensors and show the identifiers of some of the sensors I need to check out even if there happens to be some duplication. Use the index as a tiebreaker, or select one at random I don't care.

Alden