Is there a zip-like method in .Net?

.net, iteration, list, python

Solution

Update: It is built-in in C# 4 as System.Linq.Enumerable.Zip<TFirst, TSecond, TResult> Method

Here is a C# 3 version:

IEnumerable<TResult> Zip<TResult,T1,T2>
    (IEnumerable<T1> a,
     IEnumerable<T2> b,
     Func<T1,T2,TResult> combine)
{
    using (var f = a.GetEnumerator())
    using (var s = b.GetEnumerator())
    {
        while (f.MoveNext() && s.MoveNext())
            yield return combine(f.Current, s.Current);
    }
}

Dropped the C# 2 version as it was showing its age.

Problem

In Python there is a really neat function called `zip` which can be used to iterate through two lists at the same time: ``` list1 = [1, 2, 3] list2 = ["a", "b", "c"] for v1, v2 in zip(list1, list2): print v1 + " " + v2 ``` The above code should produce the following: ``` 1 a 2 b 3 c ``` I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.

Original source