如何同时循环两个列表? [英] How to loop through two lists simultaneously?

查看:208
本文介绍了如何同时循环两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经提到了以下问题:使用foreach循环遍历两个列表。我的问题是,关于选择的答案:o.DoSomething是一个比较吗?如:

 对于ListA.Concat(ListB)中的每个a 
如果(a来自ListA = a来自ListB )然后
在这里做点什么
结束如果
下一个

你可能已经猜到了,我正在使用VB.Net,并想知道如何才能做到我在这里显示的东西。这基本上是分开/独立地遍历连接列表。谢谢!

解决方案您的问题表明您需要加入操作,因为它不是你想迭代两个列表,但你也想匹配从一个列表到另一个列表的项目。

  Dim joinedLists =从item1在list1中_ 
加入item2在列表2中_
在item1.Bar Equals item2.Bar _
在{item1,item2}中选择New

对于每个对在joinedLists中
'在这里处理组合商品'
'pair.item1'
'pair.item2'
下一个

其他答案建议邮编。这只是一个函数,它接受两个序列并产生一个结果,就像连接一样,但它适合在两个列表中以FIFO方法工作。如果你需要基于平等的连接, Join 是专门为这项工作建立的。


I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

解决方案

Your question indicates that you need a Join operation, because it's not that you want to iterate over two lists, but you also want to match like items from one list to the other.

    Dim joinedLists = From item1 In list1 _
                    Join item2 In list2 _
                    On item1.Bar Equals item2.Bar _
                    Select New With {item1, item2}

    For Each pair In joinedLists
        'Do work on combined item here'
        'pair.item1'
        'pair.item2'
    Next

Other answers recommend Zip. That is simply a function that takes two sequences and produces a single result, much like join, but it is geared to work in a FIFO method over both lists. If you need connections made based on an equality, Join is the specifically built to be right tool for this job.

这篇关于如何同时循环两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆