Question

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?

Was it helpful?

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

OTHER TIPS

If you override Equals() and GetHashCode() in MyHugeType with code that determines if two instances are the same, then you won't get duplicate keys in the dictionary. Is this what you mean?

You could implement the IEquatable interface in your key class. There you specify when two objects of the class are equal to each other. After that you simply test the existence of an entry using ContainsKey and when that returns true you can obtain it using the [] operator.

You could also provide a IComparer implementation to achieve the same result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top