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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With