Take the 2-minute tour ×

I'm sure someone has answered this but I'm having trouble finding the correct search terms to locate it...

I can definitely do this by looping through all the values but I'm just checking to see if anyone knows an easier way.

Dim List1 As New List(Of Integer) From {1,3,5,7}

Dim List2 As New List(Of Integer) From {2,4,6,8}

List1.ContainsAnythingFrom(List2) = False

because there are no matching numbers in either list.

Dim List1 As New List(Of Integer) From {1,**3**,5,7}

Dim List2 As New List(Of Integer) From {2,**3**,6,8}

List1.ContainsAnythingFrom(List2) = True

because there is a 3 in each list.

I'm looking for a ContainsAnythingFrom type function.

share|improve this question
Please edit your question and add a tag for the programming language you're asking about. –  Gerrat Jan 3 '13 at 15:16
Sorry, it's VB.Net. I can't seem to find where to edit my question or tags. Found it. –  Aaron Jan 3 '13 at 15:27
See a more performant solution here: stackoverflow.com/questions/17812042/… –  jor Jul 25 '13 at 20:35
add comment

2 Answers

up vote 5 down vote accepted

You can use Enumerable.Intersect LINQ method to find common items

Dim list1 = New Integer() {1, 2, 3, 4, 5}
Dim list2 = New Integer() {3, 4, 5, 6}
Dim list3 = New Integer() {7, 8}

Dim list1HasAnyOfList2 = list1.Intersect(list2).Any()
' true

Dim list1HasAnyOfList3 = list1.Intersect(list3).Any()
' false
share|improve this answer
Exactly what I needed. Thanks! –  Aaron Jan 3 '13 at 16:03
@Aaron: Note that the second list is completely enumerated when you Intersect. Therefore, for better performance, it is recommended to have the smaller list as the second parameter. (i.e.largeList.Intersect(smallList)). –  Alex Essilfie Jan 11 '13 at 13:05
add comment
 Dim l1 As New List(Of String) From {"a", "b", "c", "d"}

    Dim l2 As New List(Of String) From {"e", "f", "c", "d"}

    Dim intersection As IEnumerable(Of String) = l1.Intersect(l2)

    '  Dim result As List(Of String) = l1.Intersect(l2).ToList()

    For Each s In intersection
share|improve this answer
add comment

Your Answer


