In order to allow short circuiting if the duplicate exists early in the list, you can add a HashSet<T>
and check the return value of its .Add
method.
By using .Any
you can short circuit the enumeration as soon as you find a duplicate.
Here's a LINQ extension method in both C# and VB:
public static bool ContainsDuplicates<T>(this IEnumerable<T> enumerable)
{
var knownKeys = new HashSet<T>();
return enumerable.Any(item => !knownKeys.Add(item));
}
<Extension>
Public Function ContainsDuplicates(Of T)(ByVal enumerable As IEnumerable(Of T)) As Boolean
Dim knownKeys As New HashSet(Of T)
Return enumerable.Any(Function(item) Not knownKeys.Add(item))
End Function
Note: to check if there are no duplicates, just change Any
to All