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

前端 未结 7 2122
轻奢々
轻奢々 2021-02-19 20:00

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

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


        
7条回答
  •  温柔的废话
    2021-02-19 20:39

    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(IEnumerable values)
    {
        var set = new HashSet();
    
        foreach (T item in values)
        {
            if (!set.Add(item))
                return false;
        }
        return true;
    }
    

提交回复
热议问题