Test if all values in a list are unique

后端 未结 8 1955
温柔的废话
温柔的废话 2020-12-03 09:22

I have a small list of bytes and I want to test that they\'re all different values. For instance, I have this:

List theList = new List

        
8条回答
  •  情深已故
    2020-12-03 10:03

    Okay, here is the most efficient method I can think of using standard .Net

    using System;
    using System.Collections.Generic;
    
    public static class Extension
    {
        public static bool HasDuplicate(
            this IEnumerable source,
            out T firstDuplicate)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
    
            var checkBuffer = new HashSet();
            foreach (var t in source)
            {
                if (checkBuffer.Add(t))
                {
                    continue;
                }
    
                firstDuplicate = t;
                return true;
            }
    
            firstDuplicate = default(T);
            return false;
        }
    }
    

    essentially, what is the point of enumerating the whole sequence twice if all you want to do is find the first duplicate.

    I could optimise this more by special casing an empty and single element sequences but that would depreciate from readability/maintainability with minimal gain.

提交回复
热议问题