Tôi ước điều này nằm trong thư viện Hệ thống, nhưng khá dễ dàng để cuộn của riêng bạn.
Dưới đây, tôi sẽ cung cấp cho bộ xương của việc viết một lớp như thế, mà sử dụng trông giống như:
var twoWayDict = new TwoWayDict<string, int>();
twoWayDict["zero"] = 0;
// twoWayDict["zero"] == 0
// twoWayDict.Reverse[0] == "zero"
twoWayDict.Reverse[1] = "one";
// twoWayDict["one"] == 1
// twoWayDict.Reverse[1] == "one"
Hãy nhớ, một Gotcha cho một cuốn từ điển hai chiều là bạn nên mong đợi tất cả các đầu vào được liên kết chặt chẽ. Nói cách khác, nếu bạn sử dụng lại khóa HOẶC một giá trị, bạn sẽ xóa dữ liệu được liên kết trước đó với một trong hai cách:
Cuối cùng, đây là một số mã mẫu. Nó tối thiểu - nó sẽ hoạt động như một nền tảng cho bất cứ ai muốn ăn thịt phiên bản của riêng họ. Lưu ý rằng tôi triển khai một lớp trình bao bọc để tôi có thể cung cấp thuộc tính "Đảo ngược" mà không trực tiếp hiển thị từ điển nội bộ.
// Generics note: K indicates "key" type and V indicates "value" type
using System.Collections.Generic;
namespace YourNamespaceHere.Collections
{
public class TwoWayDict<K, V>
{
private Dictionary<K, V> _dictKV;
private Dictionary<V, K> _dictVK;
private ReverseDict _reverseDict;
public TwoWayDict()
{
_dictKV = new Dictionary<K, V>();
_dictVK = new Dictionary<V, K>();
_reverseDict = new ReverseDict(this);
}
public ReverseDict Reverse
{
get { return _reverseDict; }
}
// TwoWayDict[key] -> value
public V this[K key]
{
get { return _dictKV[key]; }
set
{
// Remove any existing key/value pair
Remove(key);
_dictKV[key] = value;
_dictVK[value] = key;
}
}
public void Remove(K key)
{
if (_dictKV.ContainsKey(key))
{
_dictVK.Remove(_dictKV[key]);
_dictKV.Remove(key);
}
}
// Wrapper that allows TwoWayDict to expose a convenient
// 'Reverse' property.
public class ReverseDict
{
private TwoWayDict<K, V> _parent;
public ReverseDict(TwoWayDict<K, V> parent)
{
_parent = parent;
}
public K this[V reverseKey]
{
get { return _parent._dictVK[reverseKey]; }
set { _parent[value] = reverseKey; }
}
public void Remove(V value)
{
if (_parent._dictVK.ContainsKey(value))
{
_parent.Remove(_parent._dictVK[value]);
}
}
}
}
}
Có khả năng trùng lặp: http://stackoverflow.com/questions/268321 –
bản sao có thể có của [Từ điển 1 đến 1 hai chiều trong C#] (http://stackoverflow.com/questions/268321/bidirectional-1-to- 1-dictionary-in-c) –
và http://stackoverflow.com/questions/255341 – AlexFoxGill