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

前端 未结 7 2124
轻奢々
轻奢々 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:40

    A quick way of finding the first duplicate, if present, is:

    public static bool TryFindFirstDuplicate(this IEnumerable source, out T duplicate)
    {
        var set = new HashSet();
        foreach (var item in source)
        {
            if (!set.Add(item))
            {
                duplicate = item;
                return true;
            }
        }
        duplicate = default(T);
        return false;
    }
    

提交回复
热议问题