The point of hashing and Dictionary is using the unique keys bur also fast search by the key, which you can call
indexing. The speed of search is of O(1), see
http://en.wikipedia.org/wiki/Big_O_notation[
^]. If you think about it, you will understand that a non-unique key cannot be used with indexing. However, you can use objects with the same key with
Dictionary
.
For this purpose, for an element type ELEMENT and key type KEY you need to use the combined collection type:
System.Collections.Generic.Dictionary<KEY, System.Collections.Generic.List<ELEMENT>>
Isn't this clear? This is how to add an element to such combined collection:
using KeyedCollection = System.Collections.Generic.Dictionary<Key, System.Collections.Generic.List<int>>;
using ElementList = System.Collections.Generic.List<int>;
class Key {}
KeyedCollection Dictionary new KeyedCollection();
void AddKey(Key key, int element) {
ElementList list;
if (!Dictionary.TryGetValue(key, out list)) {
list = new ElementList();
Dictionary.Add(key, list);
}
list.Add(element);
}
If the key is already in dictionary, you get the dictionary value (which is list), and add your element to it, otherwise you add a new list.
You can do the similar thing using
SortedDictionary
and
SortedList
.
—SA