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?
Use the
Zip
function likeThis doesn't throw an exception, though ...
You can do something like this.
C# has no foreach that can do it how you want (that I am aware of).
In short, the language offers no clean way to do this. Enumeration was designed to be done over one enumerable at a time. You can mimic what foreach does for you pretty easily:
What to do if they are of different length is up to you. Perhaps find out which one still has elements after the while loop is done and keep working with that one, throw an exception if they should be the same length, etc.
Here's an implementation of this operation, typically called Zip:
To make it throw an exception if just one of the sequences run out of values, change the while-loop so:
In .NET 4, you can use the .Zip extension method on
IEnumerable<T>
It won't throw on unequal lengths, however. You can always test that, though.
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 anInvalidOperationException
instead.