I have a lot of code in which I do something like this
bool GetIsUnique(IEnumerable values)
{
return values.Count() == values.Distinct().Count;
}
>
Your method needs to iterate through the sequence twice, with a few of potential drawbacks:
Count
which needs to iterate the entire sequence each time. There's no reason why you shouldn't break-out early as soon as you know that there's a duplicate value.The following method only needs to iterate through the sequence once, and will break-out early as soon as any duplicate value is encountered:
bool GetIsUnique(IEnumerable values)
{
var set = new HashSet();
foreach (T item in values)
{
if (!set.Add(item))
return false;
}
return true;
}