Vb.net 使用两个列表/集合运行for循环。Visual Basic

Vb.net 使用两个列表/集合运行for循环。Visual Basic,vb.net,for-loop,Vb.net,For Loop,我只是觉得这可能是一件方便的事情 我在一个班级里有两个单独的名单。有没有一种快速的方法可以在两个列表中运行For/Next循环,而不是像本例中所要求的那样使用两个独立的For 即: 我意识到我可以用一个列表来搜索,但我要求也适用于两个不同类型控件的列表,或一个集合等。您可以用LINQ连接两个列表,然后迭代: For Each location As Location In MainLocationList.Concat(SubLocationsList) If location.id =

我只是觉得这可能是一件方便的事情

我在一个班级里有两个单独的名单。有没有一种快速的方法可以在两个列表中运行For/Next循环,而不是像本例中所要求的那样使用两个独立的For

即:


我意识到我可以用一个列表来搜索,但我要求也适用于两个不同类型控件的列表,或一个集合等。

您可以用LINQ连接两个列表,然后迭代:

For Each location As Location In MainLocationList.Concat(SubLocationsList)
    If location.id = id then
        Return location
    End If
Next
这将依次循环第一个列表中的所有元素,然后循环第二个列表中的所有元素

另一种不太冗长的方式是:

return MainLocationList.Concat(SubLocationsList).FirstOrDefault(Function(location) location.id = id)

类似的方法也可能奏效:

    Dim x As Integer = 0
    Do Until x > MainLocationList.Count - 1 Or x > SubLocationsList.Count - 1
        If MainLocationList(x) = id And SubLocationsList(x) = id Then Return MainLocationList(x)
        x += 1
    Loop
    Return Nothing 'None Found
它可能需要一些调整,因为我不知道您在每个列表中确切地查找什么,根据您的示例,它在我看来是什么样子的,就是您在匹配的每个列表中查找相同的id(此示例将以每个列表相同的索引顺序返回具有相同id的列表项)。,但这只是另一个例子,说明了如何在同一个循环中检查两个列表,您可以按整数计数,并使用整数按每个列表中的索引号检查每个实例。希望它对你有用

    Dim x As Integer = 0
    Do Until x > MainLocationList.Count - 1 Or x > SubLocationsList.Count - 1
        If MainLocationList(x) = id And SubLocationsList(x) = id Then Return MainLocationList(x)
        x += 1
    Loop
    Return Nothing 'None Found