Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bidirectional Map in .NET

Is there a .NET data structure I could use for bidirectional lookup?

Here's the problem: Serialization. My object contains a field which points to one of 10 predefined static objects. When writing to the file, I write a single character representing which of the 10 objects is being referenced. At this point, I need a lookup datastructure which will allow me to get the character code based on the object being referenced. When deserializing, I need to do the reverse. I can think of a lot of other places where I could use such a data structure.

like image 552
Agnel Kurian Avatar asked Jul 02 '09 15:07

Agnel Kurian


2 Answers

I would create a data structure that contains two generic Dictionary objects that mirror each other in such a way that the key of one represents the value of the other and vice versa. This would allow for O(1) lookup in both directions.

like image 56
Noldorin Avatar answered Oct 24 '22 07:10

Noldorin


In the case of only 10 cases that will rarely change, a couple of methods using Switch statements would probably suffice.

If you have control of the static objects, then they could all implement a new interface that returns a "serialization code" character:

public interface IStaticObject
{
    char SerializationCode { get; };
}

Therefore, going in that direction is easy: someObject.SerializationCode. Then you could also have your static objects all use a constructor that registers their SerializationCode with a singleton instance that has a Dictionary.

public class SomeStaticObject : IStaticObject
{
    public void SomeStaticObject()
    {
        StaticObjectRegistrar.Register(this.SerializationCode, this);
    }

    public char SerializationCode
    {
        get
        {
            return ?;
        }
    }
}

Deserializing, you just take the character and run it through that dictionary to get the static object back.

like image 38
Scott Whitlock Avatar answered Oct 24 '22 08:10

Scott Whitlock