編輯 - 迭代而在兩個集合在同一指數在定位
如果需求是通過兩個集合在一個「同步」的方式移動,即使用第一個集合的第一個元素與第二個集合的第一個元素,然後是第二個集合,依此類推,而不需要執行任何副作用代碼,然後參見@sll's answer並使用.Zip()
在同一索引處投影出對元素,直到其中一個集合用盡元素。
更普遍
取而代之的是foreach
的,你可以從兩個集合的IEnumerable
使用GetEnumerator()
方法訪問IEnumerator
,然後調用MoveNext()
的集合,當你需要在移動到下一個元素那個集合。這種技術在處理兩個或更多有序流時是常見的,而不需要實現流。
var stream1Enumerator = stream1.GetEnumerator();
var stream2Enumerator = stream2.GetEnumerator();
// i.e. Until stream1Enumerator runs out of
while (stream1Enumerator.MoveNext())
{
// Now you can iterate the collections independently
if (moon == 'Blue')
{
stream2Enumerator.MoveNext();
}
// Do something with stream1Enumerator.Current and stream2Enumerator.Current
}
正如其他人所指出的,如果集合被物化和支持索引,如ICollection
接口,您也可以使用標[]
運營商,雖然這種感覺時下相當笨拙:
var smallestUpperBound = Math.Min(collection1.Count, collection2.Count);
for (var index = 0; index < smallestUpperBound; index++)
{
// Do something with collection1[index] and collection2[index]
}
最後,還有一個overload of Linq's .Select()
,它提供返回的元素的索引序號,這也可能有用。
例如下面將配對的collection1
所有元素或者與collection2
前兩個元素:
var alternatePairs = collection1.Select(
(item1, index1) => new
{
Item1 = item1,
Item2 = collection2[index1 % 2]
});
什麼在第一個foreach中有第二個列表的foreach? – 2011-12-15 10:44:26
Dupe:http://stackoverflow.com/questions/5630758/how-to-loop-through-two-lists-simultaneously – Jonathan 2011-12-15 10:47:12