Is there a collection (apart from Dictionary) in the .NET framework (3.5) that throws an exception when a duplicate is added?
HashSet does not throw an exception here:
HashSet<string> strings = new HashSet<string>();
strings.Add("apple");
strings.Add("apple");
Whereas the Dictionary does:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("dude", "dude");
dict.Add("dude", "dude"); //throws exception
EDIT: Is there a collection without (Key, Value) that does this? I also want AddRange if possible...
I rolled my own:
public class Uniques<T> : HashSet<T>
{
public Uniques()
{ }
public Uniques(IEnumerable<T> collection)
{
AddRange(collection);
}
public void Add(T item)
{
if (!base.Add(item))
{
throw new ArgumentException("Item already exists");
}
}
public void AddRange(IEnumerable<T> collection)
{
foreach (T item in collection)
{
Add(item);
}
}
}