I have two enumerables: IEnumerable<A> list1
and IEnumerable<B> list2
. I would like to iterate through them simultaneously like:
foreach((a, b) in (list1, list2))
{
// use a and b
}
If they don't contain the same number of elements, an exception should be thrown.
What is the best way to do this?
You want something like the Zip
LINQ operator - but the version in .NET 4 always just truncates when either sequence finishes.
The MoreLINQ implementation has an EquiZip
method which will throw an InvalidOperationException
instead.
var zipped = list1.EquiZip(list2, (a, b) => new { a, b });
foreach (var element in zipped)
{
// use element.a and element.b
}