【问题标题】:Generic list match any value通用列表匹配任何值
【发布时间】:2013-01-03 15:15:46
【问题描述】:

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

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

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 类型的函数。

【问题讨论】:

  • 请编辑您的问题并为您询问的编程语言添加标签。
  • 对不起,这是 VB.Net。我似乎找不到在哪里编辑我的问题或标签。找到了。
  • 在此处查看更高效的解决方案:stackoverflow.com/questions/17812042/…

标签: .net vb.net linq list generics


【解决方案1】:

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

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

【讨论】:

  • 正是我需要的。谢谢!
  • @Aaron:请注意,当您Intersect 时,第二个列表是完全枚举的。因此,为了获得更好的性能,建议将较小的列表作为第二个参数。 (即largeList.Intersect(smallList))。
【解决方案2】:
 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    相关资源
    最近更新 更多