繁体   English   中英

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

[英]Check whether two lists have at least one common item

如果有两个列表:

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

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

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

list1.Intersect(list2).Any()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM