Desearía que esto estuviera en la biblioteca del sistema, pero es bastante fácil de hacer.
A continuación, voy a proporcionar el esqueleto de escribir una clase de este tipo, cuyo uso se ve como:
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"
que tener en cuenta, uno de gotcha para un diccionario bidireccional es que usted debe esperar que toda la entrada para ser estrechamente acoplado. En otras palabras, si vuelve a utilizar una clave o un valor, borrará los datos anteriores vinculados con:
twoWayDict["zero"] = 0;
// Then later...
twoWayDict.Reverse[0] = "ZERO";
// Now twoWayDict["ZERO"] == 0
// Later still...
// Exception: Key not found! "zero" was dropped when you re-used value 0
Console.WriteLine(twoWayDict["zero"]);
Por último, he aquí algunos ejemplos de código. Es mínimo: debería servir de base para cualquiera que quiera desarrollar su propia versión. Tenga en cuenta que implemento una clase contenedora para que pueda proporcionar una propiedad "Invertir" sin exponer directamente el diccionario interno.
// 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]);
}
}
}
}
}
Probable duplicado de: http://stackoverflow.com/questions/268321 –
posible duplicado de [Diccionario Bidireccional 1 a 1 en C#] (http://stackoverflow.com/questions/268321/bidirectional-1-to- 1-dictionary-en-c) –
y http://stackoverflow.com/questions/255341 – AlexFoxGill