检查两个列表是否至少有一个共同项

3
如果有两个列表:
Dim list1 As New List(Of Integer)
list1.AddRange({1, 2, 3})

Dim list2 As New List(Of Integer)
list2.AddRange({1, 4, 5})

在VB.NET中,以性能为考量,检测两个集合是否有一个或多个共同项,最好的方法是什么?尽可能地通用。
2个回答

2

在C#中(但可能也适用于VB),

list1.Intersect(list2).Any()

性能如何?在检查匹配项之前,是否会进行完整的交集操作? - jor
就性能而言,这应该不是问题,因为LINQ是惰性的。因此,只要有一个交集元素,它就会返回(前提是Intersect是惰性的,我认为它是)。 - Stephane Delcroix
1
不,我错了,在产生任何结果之前,list1将被完全迭代。 - Stephane Delcroix

2
<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

代码示例:

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)

根据我所知,使用Contains方法时,它会遍历所有元素以找到所需的元素,这非常慢。在我看来,更好的方法是先迭代一次并将值放入Hashset或Dictionary(取决于使用的.NET版本),然后分别使用Contains或ContainsKey。 - Victor Zakharov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接