2

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

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

4

2 回答 2

4

我认为 Jon Skeet 的BiDictionary课程就是你要找的。像这样使用它:

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);

这是课堂。我添加了GetByFirstGetBySecond这样您就可以更像是Dictionary's indexer 而不是像它的那样访问它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];
    }
}
于 2013-09-17T16:33:09.323 回答
0

这可能不是一种有效的方法,但这可能会有所帮助,

public class MyDictinary<TKey, TVal> : Dictionary<TKey, TVal>
    {
        private Dictionary<TKey, TVal> _dictionary;
        public new int Count { get { return _dictionary.Count; } }
        public MyDictinary()
        {
            _dictionary = new Dictionary<TKey, TVal>();
        }

        public new void Add(TKey key, TVal val)
        {
            if (UniqueValueCheck(val))
            {
                _dictionary.Add(key, val);
            }
        }

        private bool UniqueValueCheck(TVal val)
        {
            return _dictionary.Aggregate(true, (current, pair) => current && !pair.Value.Equals(val));
        }
    }

扩展字典并覆盖(在这种情况下隐藏)add 方法,并且在添加时只检查唯一值。

于 2013-09-17T17:00:19.067 回答