同时按下两个迭代器

时间:2014-03-13 09:36:51

标签: .net vb.net loops iterator

我有一个常用的For / each迭代器:

For Each food In foods
   ' Iterate over food
Next

除了foods之外,假设我有另一个列表beverages。每个列表中的元素都有一个Import字段。我想将Import元素的第beveragefood元素的第i个元素相加,并将结果放入一个新列表中(每个列表都不同来自其他人)。类似的东西:

checkout.Add(beverage.Import + food.Import)

我可以记下迭代次数并获得相关的饮料元素然后总结,但我认为这非常不优雅。我想同时迭代两个集合,一种

For Each food In foods And beverage In beverages
    checkout.Add(beverage.Import + food.Import)
Next

1 个答案:

答案 0 :(得分:2)

您正在寻找Linq的Zip方法。

var beverages = ...;
var foods = ...;

var sumSequence = foods.Zip(beverages, (food, beverage) => beverage.Import + food.Import);
foreach (var importSum in sumSequence)
{
    checkout.Add(importSum);
}

为c#代码道歉。

这是VB.NET中的一个例子

Dim beverages () As Integer = {1, 2, 3, 4}
Dim foods() As String = {"one", "two", "three"}
Dim numbersAndWords = numbers.Zip(beverages, Function(food, beverage) beverage.Import & " " & food.Import)

For Each item In numbersAndWords
    Console.WriteLine(item)
Next 

' This code produces the following output: 

' 1 one 
' 2 two 
' 3 three