2

如果有两个列表:

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 中检测它们是否具有一个或多个常见项的最佳方法是什么?尽可能这应该是通用的。

4

2 回答 2

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)
于 2013-07-23T13:44:59.657 回答
1

在 C# 中(但在 VB 中也可能有效)

list1.Intersect(list2).Any()
于 2013-07-23T13:49:05.000 回答