To ensure a short circuit, if a duplicate exists at the top of the list, you can add a HashSet<T> and check the return value of its .Add method,
Using .Any , you can short encode the listing as soon as you find the duplicate.
Here's the LINQ extension method in both C # and VB:
Csharp:
public static bool ContainsDuplicates<T>(this IEnumerable<T> enumerable) { var knownKeys = new HashSet<T>(); return enumerable.Any(item => !knownKeys.Add(item)); }
Visual Basic:
<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 for duplicates, just change Any to All
KyleMit May 22 '14 at 4:24 a.m. 2014-05-22 04:24
source share