views:

261

answers:

2

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.

+4  A: 

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.

Scott Whitlock
+4  A: 

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.

Noldorin
As long as all of the keys and values are unique this should work
Nick
In this specific question, the OP would still need to create some kind of global registry to house this data structure, and the OP needs to implement some way for all the static objects to register themselves with this global data structure. In that case, doesn't each "Static Object" already have to know about it's own representative character so it can register itself?
Scott Whitlock
This is a good idea, I would just be careful to check both .Contains before you do either .Add just so that if there is a conflict you don't pollute either dictionary.
Doug McClean
@Scott W.: I was mainly answering the general question of how the data structure could be designed... I'll give the specific application of serialisation some consideration though.
Noldorin
@Doug McClean: Indeed, that would be necessary for a robust data structure. There would be a few fine points to implementing this, but in general, it should be quite straightforward.
Noldorin