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

.net, c#, collections, ienumerable, unique

Solution

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);
}

Problem

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)

Original source