检查两个列表是否至少有一个公共项 [英] 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最好的方法是检测它们是否有一个或多个公共项目?
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.
推荐答案
<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)
这篇关于检查两个列表是否至少有一个公共项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文