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?
Go with IEnumerable.GetEnumerator, so you can move around the enumerable. Note that this might have some really nasty behavior, and you must be careful. If you want to get it working, go with this, if you want to have maintainable code, use two foreach.
You could create a wrapping class or use a library (as Jon Skeet suggests) to handle this functionality in a more generic way if you are going to use it more than once thru your code.
The code for what I suggest: