双向映射列表

Tom*_*ove 5 c# mapping

我需要在一个列表中保存2个值,这样我的所有位置和我的控制板都在一个列表中.我正在使用词典,但我发现只有一种方式映射.有没有人有任何建议,除了二维数组?

Cha*_*ana 7

这可能有所帮助:

 public class BiDirectionalDictionary<L, R>
{
    private readonly Dictionary<L, R> leftToRight = new Dictionary<L, R>();
    private readonly Dictionary<R, L> rightToLeft = new Dictionary<R, L>();
    public void Add(L leftSide, R rightSide)
    {
        if (leftToRight.ContainsKey(leftSide) ||
            rightToLeft.ContainsKey(rightSide))
            throw new DuplicateNameException();
        leftToRight.Add(leftSide, rightSide);
        rightToLeft.Add(rightSide, leftSide);
    }
    public L this[R rightSideKey]
    { get { return rightToLeft[rightSideKey]; } }
    public R this[L leftSideKey]
    { get { return leftToRight[leftSideKey]; } }
    public bool ContainsKey(L leftSideKey)
    { return leftToRight.ContainsKey(leftSideKey); }
    public bool ContainsKey(R rightSideKey)
    { return rightToLeft.ContainsKey(rightSideKey); }
}
 [Serializable]
public class DuplicateNameException : SystemException
{
    protected DuplicateNameException(
           SerializationInfo info, StreamingContext context);
    public DuplicateNameException();
    public DuplicateNameException(string s);
    public DuplicateNameException(string message, 
           Exception innerException);
}
Run Code Online (Sandbox Code Playgroud)

如果左侧和右侧是相同类型,则会出现问题...即,如果您尝试,它将无法正常工作

var myBiDireDict = new BiDirectionalDictionary<DateTime, DateTime>();
Run Code Online (Sandbox Code Playgroud)


Aar*_*ght 6

如果您不关心反向映射的线性搜索性能(无论如何都可以使用2D数组),您可以轻松地使用字典作为双向映射:

var dictionary = new Dictionary<string, int>();
// Fill it up...
int forwardMapResult = dictionary["SomeKey"];
string reverseMapResult = dictionary.Where(kvp => kvp.Value == 5).First().Key;
Run Code Online (Sandbox Code Playgroud)

如果查找速度是一个问题,那么你必须维护两个字典 - 一个用于正向查找,一个用于反向.或者使用内存可索引的数据库,例如SQLite.