通用列表匹配任何值

时间:2013-01-03 15:15:47

标签: .net vb.net linq list generics

我确定有人已经回答了这个问题,但我找不到正确的搜索字词来找到它...

我绝对可以通过循环遍历所有值来实现这一点,但我只是在检查是否有人知道更简单的方法。

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

因为两个列表中都没有匹配的数字。

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

因为每个列表中都有3个。

我正在寻找 ContainsAnythingFrom 类型的功能。

2 个答案:

答案 0 :(得分:5)

您可以使用Enumerable.Intersect LINQ方法查找常用项

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

答案 1 :(得分:0)

 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
        Console.WriteLine(s)
    Next