Question

I could convert them to lists and just use a regular for loop with indexes, but I'm wondering if there's a way to do it that keeps them as IEnumerables.

Was it helpful?

Solution

By default there is no way but it's not difficult to add an extension method to make it a bit easier. I excluded some error checking to ensure they were both the same length for brevity.

public static void ForEachPair<T1,T2>(
  this IEnumerable<T1> source1, 
  IEnumerable<T2> source2,
  Action<T1,T2> del) {
  using ( var e1 = source1.GetEnumerator() )
  using ( var e2 = source2.GetEnumerator() ) {
    while ( e1.MoveNext() && e2.MoveNext() ) {
      del(e1.Current, e2.Current);
    }
  }
}

Now you can do the following

var list = GetSomeList();
var otherList = GetSomeOtherList();
list.ForEachPair(otherList, (x,y) => 
{
   // Loop code here
});

OTHER TIPS

I think you want the new Zip feature from .NET 4.0. Eric Lippert blogged about it recently and included a simple form of the implementation.

It's also in MoreLINQ, in Zip.cs, which allows for different options if the sequences aren't the same length. The "default" is to act like .NET 4.0, stopping when either sequence runs out of elements. Alternatives are to pad the shorter sequence or throw an exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top