views:

280

answers:

4

Python's zip function does the following:

a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)

result

[[1, 6], [2, 7], [3, 8]]
+2  A: 

Solution 1:

IEnumerable<KeyValuePair<T1, T2>> Zip<T1, T2>(
    IEnumerable<T1> a, IEnumerable<T2> b)
{
    var enumeratorA = a.GetEnumerator();
    var enumeratorB = b.GetEnumerator();
    while (enumeratorA.MoveNext())
    {
        enumeratorB.MoveNext();
        yield return new KeyValuePair<T1, T2>
        (
            enumeratorA.Current,
            enumeratorB.Current
        );
    }
}
Jader Dias
+5  A: 

How about this?

C# 4.0 LINQ'S NEW ZIP OPERATOR

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
        this IEnumerable<TFirst> first,
        IEnumerable<TSecond> second,
        Func<TFirst, TSecond, TResult> func);
tanascius
Beautiful!!!!!!
Jader Dias
+5  A: 

Solution 2: Similar to C# 4.0 Zip, but you can use it in C# 3.0

    public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
        this IEnumerable<TFirst> first,
        IEnumerable<TSecond> second,
        Func<TFirst, TSecond, TResult> func)
    {
        using(var enumeratorA = first.GetEnumerator())
        using(var enumeratorB = second.GetEnumerator())
        {
            while (enumeratorA.MoveNext())
            {
                enumeratorB.MoveNext();
                yield return func(enumeratorA.Current, enumeratorB.Current);
            }
        }
    }
Jader Dias
it throws exceptions when second is shorter than first, as expected
Jader Dias
You've forgotten to dispose your enumerators.
Eric Lippert
@Eric thanks for the correction. I edited the answer
Jader Dias
+1  A: 

Also take a look at Cadenza which has all sorts of nifty utility methods.

Specifically look at the Zip extension methods here: http://gitorious.org/cadenza/cadenza/blobs/master/src/Cadenza/Cadenza.Collections/Enumerable.cs#line1303

EvilRyry