3

可能重复:
具有唯一键和值的 C# 字典类型

我想确保字典具有唯一的键和值。有没有办法在建立我自己的课程之外添加这种验证?这是我能想到的对字典中的值进行验证的唯一方法。但是,也许我可以添加一些我似乎无法通过谷歌找到的属性。

如果有帮助,我也希望将此字典与 WPF 绑定一起使用。

4

2 回答 2

5

根据定义,字典键是唯一的。确保字典值的唯一性与检查每个数组或集合成员是否唯一的方式相同。

假设您的 TValue 类型实现.NET 3.5 引入了HashSet<T>哪些加快速度Equals(TValue)

HashSet<TValue> seenValues = new HashSet<TValue>();
foreach(TKey key in myDictionary) {
    if( seenValues .Contains( myDictionary[key] ) ) throw new Exception("Dictionary contains duplicate item.");
    seenValues .Add( myDictionary[key] );
}
于 2012-09-05T17:59:24.743 回答
0

您可以尝试使用这个双向字典类:

public class Map<T1, T2>
{
    private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    private Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();

    public Map()
    {
        this.Forward = new Indexer<T1, T2>(_forward);
        this.Reverse = new Indexer<T2, T1>(_reverse);
    }

    public class Indexer<T3, T4>
    {
        private Dictionary<T3, T4> _dictionary;
        public Indexer(Dictionary<T3, T4> dictionary)
        {
            _dictionary = dictionary;
        }
        public T4 this[T3 index]
        {
            get { return _dictionary[index]; }
            set { _dictionary[index] = value; }
        }
    }

    public void Add(T1 t1, T2 t2)
    {
        _forward.Add(t1, t2);
        _reverse.Add(t2, t1);
    }

    public Indexer<T1, T2> Forward { get; private set; }
    public Indexer<T2, T1> Reverse { get; private set; }
}

你可以像这样使用它:

var map = new Map<int, string>();

map.Add(42, "Hello");

Console.WriteLine(map.Forward[42]);
// Outputs "Hello"

Console.WriteLine(map.Reverse["Hello"]);
//Outputs 42

这是一个相当简单的实现。您可能需要公开一些底层字典功能,但至少这是一个开始。

于 2012-09-06T04:18:44.987 回答