Check whether two lists have at least one common item

梦想与她 提交于 2019-12-12 16:52:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!