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

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

    I think it depends on what you want to do if there are non unique values. @Jamiec's Or @LukeH's answer are great answers and probably best for pure speed, but it can't tell you where issues are.

    You might also consider something like

    var group = values.GroupBy(x => x);
    return group.Any(g => g.Count() > 1);
    

    On it's own its worse than the HashSet implementation. But if you keep that group around you can find which elements are duplicated.

    var group = values.GroupBy(x => x);
    return group.Where(g => g.Count() > 1);
    

    Or

    var group = values.GroupBy(x => x);
    return group.Where(g => g.Count() > 1).Select(g => g.Key);
    

    Thinking about it with GroupBy lets you keep your options open for what to do next. But if all you care about is knowing if all values are unique I'd go with the HashSet

    0 讨论(0)
提交回复
热议问题