Bi-directional Dictionary implementation
Bi-directional Dictionary implementation
There were several times, during my short development career, that I’ve
used Dictionary<TKey, TValue>. It may not be on most cases, but I’m sure
in many of them, I needed to find a dictionary item by it’s value whereas
the dictionary’s values were unique as well as it’s keys.
This led me to the motivation of developing a dictionary that will support
bi-directional access.
What were the requirements?
1. Access dictionary[value] will return it’s key the same way dictionary[key]
return it’s value.
2. Performance will be effected only by a constant (O(1) to get and set dictionary item
the same as in regular Dictionary<TKey, TValue>)
3. The bidirectional dictionary will implement all interfaces that Dictionary<TKey, TValue>
does.
Implementation:
The requirements listed above have led me to use Dictionary<TKey, TValue> qualities by
using an internal two dictionaries. One will act as Dictionary<TKey, TValue> and the other
will be the other way around (Dictionary<TValue, TKey>).
I’ve set two indexers (one for each direction). The add / remove methods calls their
corresponding methods on their internal dictionaries.
When trying to add the same value twice (with different keys) an exception is thrown.
Limitations:
When using the bi-directional dictionary with key and value having the same type, there
is an ambiguity when calling dictionary[key] and dictionary[value].
I’ve had two choices – Change the whole interface of the opposite direction access and
having all “by value” access be explicit, or removing the support for same type. On that
case, I’ve preferred keeping the same interface for by-key and by-value access and
therefore removed support for the same type.
My implementation can be downloaded here (don’t forget to change the extension to .cs)
Another implementation that does support same type dictionary I’ve found on a
StackOverflow forum thread here .
This class can run on Framework 2.0 and above