Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET collection that throws an exception when a duplicate is added

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);
        }
    }
}
like image 843
geejay Avatar asked Nov 05 '09 09:11

geejay


People also ask

Which collection does not allow duplicates in C#?

Thus, HashSet is a generic collection, that does not allow duplicates.

What happens if we add duplicate values in HashSet C#?

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.


1 Answers

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 */
like image 153
Björn Avatar answered Oct 12 '22 03:10

Björn