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

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

    I would make this a nice extension method

    public static bool IsUnique(this IEnumerable list)
    {
        var hs = new HashSet();
        return list.All(hs.Add);  
    }
    

    Checks that all items can be added to a HashSet.

提交回复
热议问题