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

时间:2013-07-23 13:45:00

标签: vb.net performance list generics comparison

如果有两个列表:

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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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

list1.Intersect(list2).Any()