Rich
Rich

Reputation: 2347

Is there a way to retrieve a Dictionary key using an equivalent key?

I'm using a custom class as a key for a Dictionary(TKey, TValue). The class overrides GetHashCode and Equals, etc.

What I'd like to be able to do is add a key/value pair; later, generate a new key that is equivalent to the first key (same hash code, Equals returns true), and, using this equivalent key, retrieve not only the value, but also a reference to the original key that was first added to the Dictionary.

Example:

var keyA = new KeyClass("abc123");
var keyB = new KeyClass("abc123"); // same as far as dictionary is concerned

var dict = new Dictionary<KeyClass, Object>();

dict.Add(keyA, value);

Now how can I get a reference to keyA from the Dictionary using keyB?

It seems like this should be easy to do without enumerating the Keys collection, since the Dictionary has these keys hashed already, but I can't find anything built into the Dictionary class. Am I missing something? As it stands now I'll either have to use a bidirectional dictionary and do a reverse lookup, or (my preference in this case) "enhance" the class I'm using for values so they store references to the original keys.

Upvotes: 1

Views: 104

Answers (1)

cat916
cat916

Reputation: 1361

Well, @AD.Net is appropriate answer which is mostly true when overriding GetHashCode() and Equals()

public class KeyClass 
{

   public readonly string key;

   public KeyClass(string key)
   {
      this.key = key;
   }

   public override bool Equals(object other)
   {
       if (other == null)
         return false;

       // Casting object other to type KeyClass
       KeyClass obj = other as KeyClass;
       if (obj == null)
         return false;

        return this.key == other.key;
   }

   public override int GetHashCode()
   {
        return this.key.GetHashCode();
   }
}

Upvotes: 1

Related Questions