.net 数据结构具有一对一映射?

标签 .net

是否有用于 key - key 对的内置数据结构?我正在构建一个交叉引用表,其中引用的每一“侧”都是唯一的,并且与另一侧的一个值完全对应。

例如,如果我有一组颜色名称和颜色代码,我希望通过颜色代码或名称来查找颜色。名称查找将返回颜色代码,而代码查找将返回颜色名称。

最佳答案

我认为 Jon Skeet 的 BiDictionary class就是您正在寻找的。像这样使用它:

BiDictionary<string, string> colors = new BiDictionary<string, string>();
colors.Add("Green", "00FF00");
colors.Add("Red", "FF0000");
colors.Add("White", "FFFFFF");
string code = colors.GetByFirst("Red");
string name = colors.GetBySecond("FF0000");
Console.WriteLine(code);
Console.WriteLine(name);

这就是类(class)。我添加了 GetByFirstGetBySecond ,以便您可以更像 Dictionary 的索引器而不是像 TryGetValue 那样访问它

using System;
using System.Collections.Generic;

class BiDictionary<TFirst, TSecond>
{
    IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
    IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

    public void Add(TFirst first, TSecond second)
    {
        if (firstToSecond.ContainsKey(first) ||
            secondToFirst.ContainsKey(second))
        {
            throw new ArgumentException("Duplicate first or second");
        }
        firstToSecond.Add(first, second);
        secondToFirst.Add(second, first);
    }

    public bool TryGetByFirst(TFirst first, out TSecond second)
    {
        return firstToSecond.TryGetValue(first, out second);
    }

    public TSecond GetByFirst(TFirst first)
    {
        return firstToSecond[first];
    }

    public bool TryGetBySecond(TSecond second, out TFirst first)
    {
        return secondToFirst.TryGetValue(second, out first);
    }

    public TFirst GetBySecond(TSecond second)
    {
        return secondToFirst[second];
    }
}

关于.net 数据结构具有一对一映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18855065/

相关文章:

c# - 是否可以在程序集中扫描具有特定属性的方法?

c# - GraphQL : Not Getting EF Related objects after implementing Types

.net - 如何通过反射检索字符串并将其升序连接

c# - File.OpenWrite 给出错误,而 FileStream(sFile, FileMode.Open, FileAccess.ReadWrite) 没有

.net - 如何使用 .NET XML API 删除 xmlns 属性

c# - 捕获流输出到字符串

c# - 如何从数据库刷新 ObjectContext 缓存?

c# - 在项目之外访问图像的最佳方式?

asp.net - 是否使用 TPL 或 async/await

.net - RoutedCommand和RoutedUICommand有什么区别?