在C#中Dictionary就是hashtable,只是用起来有泛型更方便,它位于System.Collections.Generic,其定义为:
[SerializableAttribute]
[ComVisibleAttribute(false)]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>,
IDictionary, ICollection, IEnumerable,
ISerializable, IDeserializationCallback
我们常常用key来得到value,例如:
string v = dict[key1];
但 如何用value来得到key? 例如:
string k = dict[value1];
这种需求是常见的,当然你可以遍历所有的value来定位key,或者用很炫的语法糖LINQ,像这样:
MyDict.FirstOrDefault(pair => pair.Value == "the value you want").Key;
但酱紫就不大约O(1)时间了。
一种做法是创建一个自定义的数据结构,里面用空间换时间,存储另外一个value,key的Dictionary,代码如下:
/// <summary>
/// This is a dictionary guaranteed to have only one of each value and key.
/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.
/// </summary>
/// <typeparam name="TFirst">The type of the "key"</typeparam>
/// <typeparam name="TSecond">The type of the "value