Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I verify a collection of values is unique (contains no duplicates) in C#

Surely there is an easy way to verify a collection of values has no duplicates [using the default Comparison of the collection's Type] in C#/.NET ? Doesn't have to be directly built in but should be short and efficient.

I've looked a lot but I keep hitting examples of using collection.Count() == collection.Distinct().Count() which for me is inefficient. I'm not interested in the result and want to bail out as soon as I detect a duplicate, should that be the case.

(I'd love to delete this question and/or its answer if someone can point out the duplicates)

like image 542
Ruben Bartelink Avatar asked Jul 18 '13 11:07

Ruben Bartelink


People also ask

Can list have duplicates in C#?

A List may have duplicate elements—to eliminate these, we call Distinct(). We can use a method like ToList() to go from an IEnumerable to a List again. Distinct example.


1 Answers

Okay, if you just want to get out as soon as the duplicate is found, it's simple:

// TODO: add an overload taking an IEqualityComparer<T>
public bool AllUnique<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    var distinctItems = new HashSet<T>();
    foreach (var item in source)
    {
        if (!distinctItems.Add(item))
        {
            return false;
        }
    }
    return true;
}

... or use All, as you've already shown. I'd argue that this is slightly simpler to understand in this case... or if you do want to use All, I'd at least separate the creation of the set from the method group conversion, for clarity:

public static bool IsUnique<T>(this IEnumerable<T> source)
{
    // TODO: validation
    var distinctItems = new HashSet<T>();
    // Add will return false if the element already exists. If
    // every element is actually added, then they must all be unique.
    return source.All(distinctItems.Add);
}
like image 90
Jon Skeet Avatar answered Sep 27 '22 23:09

Jon Skeet