Requirement: In an unsorted List, determine if a duplicate exists. The typical way I would do this is an n-squared nested loop. I'm wondering how others solve this. Is there an elegant, high performance method in Linq? Something generic that takes a lambda or a comparer would be nice.
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:
CSharp:
<!-- language: lang-cs -->public static bool ContainsDuplicates<T>(this IEnumerable<T> enumerable)
{
var knownKeys = new HashSet<T>();
return enumerable.Any(item => !knownKeys.Add(item));
}
Visual Basic:
<!-- language: lang-vb --><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