2013-07-23 68 views
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的最佳途徑,在性能方面,以檢測他們是否有一個或多個公共項目?儘可能地這應該是通用的。

回答

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

着如何包含的作品,IIRC,它會遍歷所有元素找到你需要一個,這是非常緩慢的。在我看來,更好的方法是迭代一次並將值放入Hashset或Dictionary(取決於正在使用的.NET版本),然後使用[Contains](http://msdn.microsoft.com/en-us /library/bb356440.aspx)或[ContainsKey](http://msdn.microsoft.com/en-us/library/kw5aaea4.aspx)。 – Neolisk

+0

好抓,更新了功能,現在好點? – jor

+0

是的,我如何接受你的答案?開玩笑,+1。 :) – Neolisk

1

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

list1.Intersect(list2).Any() 
+0

性能如何,在檢查匹配項目之前,這不是完全相交嗎? – jor

+1

如果我們談論開發者的表現,這是一個勝利:) –

+0

和性能明智,它不應該是一個問題,因爲LINQ是懶惰的。所以只要有一個元素相交,它就會返回(假設Intersect是懶惰的,我認爲是) –

相關問題