Usuful methods – 10 of N – Dictionary with unique values
The .NET Dictionary<TKey, TValue> is a great class.
MSDN:
The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table
I’m using this class very often. I’m not going to explain when to use a dictionary, an array, a sorted array or a tree or any other data structures – there is a lot of articles on this subject on the net. Instead I’ll extend the class and I’ll constraint the set of values to be unique which will give us a one-to-one mapping.It’s a very simple thing to do.
public class UniqueValuesDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new void Add(TKey key, TValue value)
{
if (this.Values.Count > 0)
{
bool hasDuplicates = this.Values.Contains(value);
if (hasDuplicates)
{
throw new ArgumentException("An element with the same value already exists.");
}
}
base.Add(key, value);
}
}
And here’s an example which demonstrates how this class will help us find errors
var lookup = new Dictionary<int, string>();
lookup.Add(1, "One");
lookup.Add(2, "One"); // No exception as expected
var uniqueLookup = new UniqueValuesDictionary<int, string>();
uniqueLookup.Add(1, "One");
uniqueLookup.Add(2, "One"); // Here we'll get an exception

Leave a Reply