问题
If there are two lists:
Dim list1 As New List(Of Integer)
list1.AddRange({1, 2, 3})
Dim list2 As New List(Of Integer)
list2.AddRange({1, 4, 5})
What is the best way in VB.NET, in terms of performance, to detect whether they have one or more common items? As much as possible this should be generic.
回答1:
<System.Runtime.CompilerServices.Extension()> _
Function ContainsAny(Of T)(col1 As IEnumerable(Of T), col2 As IEnumerable(Of T)) As Boolean
' performance checks
If col1 Is Nothing OrElse col2 Is Nothing Then Return False
If col1 Is col2 Then Return True
' compare items, using the smallest collection
If col1.Count < col2.Count Then
Dim hs1 As New HashSet(Of T)(col1)
For Each v In col2
If hs1.Contains(v) Then Return True
Next
Else
Dim hs2 As New HashSet(Of T)(col2)
For Each v In col1
If hs2.Contains(v) Then Return True
Next
End If
Return False
End Function
Code example:
Dim list1 As New List(Of Integer)
list1.AddRange({1, 2, 3})
Dim list2 As New List(Of Integer)
list2.AddRange({1, 4, 5})
Dim anyMatch As Boolean = list1.ContainsAny(list2)
回答2:
In C# (but probably valid in VB as well)
list1.Intersect(list2).Any()
来源:https://stackoverflow.com/questions/17812042/check-whether-two-lists-have-at-least-one-common-item