[英]What data-structure should I use to represent many-to-one mapping?
我有一组可以通过多个键访问的对象,我应该使用什么结构来表示此内存? 我唯一需要的操作是一个查找程序,它将返回给我键的值。
例如:
key: {"a","aa","aaa"}, value {1}
key: {"b","bb","bbb"}, value {2}
key: {"c","cc","ccc"}, value {3}
我会这样使用它:
MyStruct.Get["a"]; // return 1
MyStruct.Get["aa"]; // return 1
MyStruct.Get["bbb"]; // return 2
MyStruct.Get["d"]; // return null
您应该使用字典 。 您可以像这样使用它:
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
}
或者,您可以像这样进行查找:
int result1 = myDict["a"]; //throws exception when the value is not present
在为TKey参数使用自己的类时要小心。 如果这样做,则应重写.Equals和.GetHashCode方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.