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);
}
}
}
Thus, HashSet is a generic collection, that does not allow duplicates.
If we insert duplicate values to the Set, we don't get any compile time or run time errors. It doesn't add duplicate values in the set. Below is the add() method of the set interface in java collection that returns Boolean value either TRUE or FALSE when the object is already present in the set.
But the HashSet.Add method returns false if the value already is present - isn't that enough?
HashSet<string> set = new HashSet<string>();
...
if (!set.Add("Key"))
/* Not added */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With