I have a lot of code in which I do something like this
bool GetIsUnique(IEnumerable values)
{
return values.Count() == values.Distinct().Count;
}
>
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