循环浏览不同类型对象的组合列表

时间:2019-04-23 17:47:27

标签: vb.net

我有两个列表。一个具有“ Foo”类型,另一个具有“ Bar”类型。

Foo和Bar都恰好具有“ a”的属性。

有没有办法遍历这两个列表,使它们相互组合以检查属性a的值?

伪代码

for each item in FooList + BarList
    if item.a = "this is the value" then
        return True
    end if
next

我不想单独浏览列表,尽管我知道这是可行的。

我不希望由于添加列表而修改原始列表。

Linq答案是可以接受的。


上下文是我正在搜索DXF文件中的所有文本。这些文本中的一些称为MTEXTS,而另一些简称为TEXT。 MTEXT只是具有更多功能的文本,但是无论其他属性是什么,这两种东西显然都包含“值”的公共属性。


更新

基于接受的答案中的代码,我能够提出一种快速的内联方法。

for each item in new List(Of Object)().Concat(FooList).Concat(BarList)
    if item.a = "this is the value" then
        return True
    end if
next

2 个答案:

答案 0 :(得分:1)

我确定这会引起很多人的不满,但这是实现此目的的一种方法。将列表转换为对象,然后将它们Concat()在一起,以便您枚举它们。现在使用CallByName()从他们那里获取“ A”属性:

Public Class Form1

    Private FooList As New List(Of Foo)
    Private BarList As New List(Of Bar)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FooList.Add(New Foo() With {.A = "Bob"})
        FooList.Add(New Foo() With {.A = "Dora"})
        BarList.Add(New Bar() With {.A = "Pikachu"})
        BarList.Add(New Bar() With {.A = "Aang"})
        BarList.Add(New Bar() With {.A = "Joe"})
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For Each O As Object In FooList.Cast(Of Object).Concat(BarList.Cast(Of Object))
            Dim A As String = CallByName(O, "A", CallType.Get)
            Debug.Print(A)
        Next
    End Sub

End Class

Public Class Foo

    Public Property A As String

End Class

Public Class Bar

    Public Property A As String

End Class

答案 1 :(得分:1)

FWIW,这是使用匿名类型和LINQ的解决方案

Private foos As New List(Of Foo)
Private bars As New List(Of Bar)

Sub Main()
    foos.Add(New Foo() With {.A = "this is not the value"})
    foos.Add(New Foo() With {.A = "this is not the value"})
    bars.Add(New Bar() With {.A = "this is the value"})
    bars.Add(New Bar() With {.A = "this is not the value"})
    Console.WriteLine($"Found the value: {fooBar()}. Press any key to exit!")
    Console.ReadLine()
End Sub

Private Function fooBar() As Boolean
    Dim combinedList = foos.Select(Function(f) New With {f.A}).Concat(bars.Select(Function(f) New With {f.A}))
    For Each item In combinedList
        If item.A = "this is the value" Then Return True
    Next
    Return False
End Function

Public Class Foo
    Public Property A As String
End Class

Public Class Bar
    Public Property A As String
End Class