Reputation: 3496
Good morning, afternoon or night,
Is there anything like an injective Dictionary
in .NET, or at least any way I can force a Dictionary
to define an injective mapping?
Thank you very much.
Upvotes: 0
Views: 211
Reputation: 4502
You can use it like this
public class InjectiveDictionary<T, V> : Dictionary<T, V>
{
public new void Add(T key, V value)
{
if (this.ContainsValue(value))
{
throw new Exception("value already used");
}
base.Add(key, value);
}
public InjectiveDictionary(Dictionary<T, V> dict)
{
foreach (var entry in dict)
{
this.Add(entry.Key, entry.Value);
}
}
public InjectiveDictionary()
{
}
}
Upvotes: 1