Yongke Bill Yu Yongke Bill Yu - 2 months ago 14x
C# Question

What data-structure should I use to represent many-to-one mapping?

I have a set of objects that can be accessed with multiple keys, what structure should I use to represent this in memory? The only operation I require is a finder that will return me the value giving a key.

For example:

key: {"a","aa","aaa"}, value {1}
key: {"b","bb","bbb"}, value {2}
key: {"c","cc","ccc"}, value {3}

I would use it like this:

MyStruct.Get["a"]; // return 1
MyStruct.Get["aa"]; // return 1
MyStruct.Get["bbb"]; // return 2
MyStruct.Get["d"]; // return null


You should use a Dictionary. And you can use it like this:

Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("a", 1);
myDict.Add("aa", 1);
myDict.Add("c", 3);

int result;
if (myDict.TryGetValue("a", out result)){
   //do something with result

Or you can do the lookup like this:

int result1 = myDict["a"]; //throws exception when the value is not present  

Be careful when using your own classes for the TKey parameter. If you do so, you should override the .Equals and .GetHashCode methods.