unfortunately Dictionary
provided by framework doesn't provide this feature.
Fastest workaround would be build something like this
public class UniqueValueDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new void Add(TKey key, TValue value)
{
if (this.ContainsValue(value))
{
throw new ArgumentException("value already exist");
}
base.Add(key, value);
}
public new TValue this[TKey key]
{
get
{
return base[key];
}
set
{
if (this.ContainsValue(value))
{
throw new ArgumentException("value already exist");
}
base[key] = value;
}
}
}
Or something like the following(which is better in performance but not memory)
public class UniqueValueDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
Dictionary<TValue, TKey> valueAsKey = new Dictionary<TValue, TKey>();
public new void Add(TKey key, TValue value)
{
if (valueAsKey.ContainsKey(value))
{
throw new ArgumentException("value already exist");
}
base.Add(key, value);
valueAsKey.Add(value, key);
}
public new TValue this[TKey key]
{
get
{
return base[key];
}
set
{
if (valueAsKey.ContainsKey(value))
{
throw new ArgumentException("value already exist");
}
if (!this.ContainsKey(key))
{
this.Add(key, value);
}
else
{
base[key] = value;
valueAsKey[value] = key;
}
}
}
//You may need to handle remove as well
}
Note:this will work only when you use UniqueValueDictionary<TKey, TValue>
type, If you cast to Dictionary<TKey, TValue>
you can add duplicate values.
As pointed in comments you can build something like this inheriting from IDictionary<TKey, TValue>
not Dictionary<TKey, TValue>
taking this as an idea.