Gluip Gluip - 3 months ago 11
C# Question

Best way to find out if IEnumerable<> has unique values

I have a lot of code in which I do something like this

bool GetIsUnique(IEnumerable<T> values)
{
return values.Count() == values.Distinct().Count;
}


Is there a better faster nicer way to do this?

Answer

Your method needs to iterate through the sequence twice, with a few of potential drawbacks:

  1. Iterating twice will be slower than iterating once for sequences of any significant size.
  2. Some sequences will throw an exception if you try to iterate them more than once; others might return different results for subsequent iterations.
  3. Your method uses Count which needs to iterate the entire sequence each time. There's no reason why you shouldn't break-out early as soon as you know that there's a duplicate value.

The following method only needs to iterate through the sequence once, and will break-out early as soon as any duplicate value is encountered:

bool GetIsUnique<T>(IEnumerable<T> values)
{
    var set = new HashSet<T>();

    foreach (T item in values)
    {
        if (!set.Add(item))
            return false;
    }
    return true;
}