Search code examples
c#.netkeysorteddictionarystring-interning

Get a key equal to an item from SortedDictionary?


Is there any way to retrieve a key from a SortedDictionary that is equal to a given object? To illustrate, lets say I create a dictionary that has a fairly memory-heavy, immutable key type:

var dictionary = SortedDictionary<MyHugeType, int>();
var myEnormousKey = new MyHugeType();

dictionary[myEnormousKey] = 123;

Then later on, I do something like this:

// This is a new instance, but it's identical to the previous key
var myIdenticalKey = new MyHugeType();

if(dictionary.ContainsKey(myIdenticalKey)) {
    myIdenticalKey = dictionary.GetKeyEqualTo(myIdenticalKey);
}

// Use myIdenticalKey reference...

Obviously, SortedDictionary does not have a "GetKeyEqualTo" method. But is there some way I could achieve a similar effect? This would basically have the effect of intern-ing the heavy key objects so that identical instances could be discarded. I know I can do this using the SortedList class by retrieving the key's index and subsequently its matching object instance, but SortedDictionary's consistent insertion performance would be better for my uses.

Short of iterating through all the dictionary's keys to search for a match, or writing my own BST class, is there any way to achieve this end with .NET's built in collections?


Solution

  • You could change your value object from int to a struct or class containing both the value and the original key. Then to access the original key you can do:

    dictionary[myIdenticalKey].OriginalKey
    

    and for the value something like:

    dictionary[myIdenticalKey].Value