21

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]]
Jader Dias
  • 88,211
  • 155
  • 421
  • 625
  • 3
    Note that zip can take any number of arguments, not just two, as in this example. The answers so far are focused on this two-iterable case, it seems to me. – Jeffrey Harris Mar 12 '10 at 00:42

6 Answers6

13

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);
Jader Dias
  • 88,211
  • 155
  • 421
  • 625
tanascius
  • 53,078
  • 22
  • 114
  • 136
  • 10
    The name is the same, but the action is completely different. Linq's Zip() can be used to produce python-zip effect on 2 input sequences, but has nothing to do with more than 2 sequences. – C-F Jun 18 '14 at 21:02
7

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
  • 88,211
  • 155
  • 421
  • 625
2

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
  • 88,211
  • 155
  • 421
  • 625
2

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

Specifically look at the Zip extension methods under Cadenza.Collections.EnumerableCoda.

Adam Bradley
  • 1,575
  • 15
  • 14
Ryan Bair
  • 2,614
  • 3
  • 18
  • 18
1

Here's a more modern rendition of Python's zip:

public static IEnumerable<(T1, T2)> Zip<T1, T2>(this IEnumerable<T1> t1, IEnumerable<T2> t2)
{
    using var t1e = t1.GetEnumerator();
    using var t2e = t2.GetEnumerator();
    while (t1e.MoveNext() && t2e.MoveNext())
        yield return (t1e.Current, t2e.Current);
}

public static IEnumerable<(T1, T2, T3)> Zip<T1, T2, T3>(this IEnumerable<T1> t1, IEnumerable<T2> t2, IEnumerable<T3> t3)
{
    using var t1e = t1.GetEnumerator();
    using var t2e = t2.GetEnumerator();
    using var t3e = t3.GetEnumerator();
    while (t1e.MoveNext() && t2e.MoveNext() && t3e.MoveNext())
        yield return (t1e.Current, t2e.Current, t3e.Current);
}

It's easy to make more extensions that handle more IEnumerables at once, I've kept it to the 2 and 3 versions for brevity.

micahneitz
  • 133
  • 2
  • 9
0

I just have come across the same problem. .NET library does not offer the solution, so I made it by myself. Here is my solution.

The Pivot method is made as extension to IEnumerable<IEnumerable<T>>. It requires all the sequences' elements to be of the same type T.

public static class LinqUtil
{
    /// <summary>
    /// From a number of input sequences makes a result sequence of sequences of elements
    /// taken from the same position of each input sequence.
    /// Example: ((1,2,3,4,5), (6,7,8,9,10), (11,12,13,14,15)) --> ((1,6,11), (2,7,12), (3,8,13), (4,9,14), (5,10,15))
    /// </summary>
    /// <typeparam name="T">Type of sequence elements</typeparam>
    /// <param name="source">source seq of seqs</param>
    /// <param name="fillDefault">
    /// Defines how to handle situation when input sequences are of different length.
    ///     false -- throw InvalidOperationException
    ///     true  -- fill missing values by the default values for the type T.
    /// </param>
    /// <returns>Pivoted sequence</returns>
    public static IEnumerable<IEnumerable<T>> Pivot<T>(this IEnumerable<IEnumerable<T>> source, bool fillDefault = false)
    {
        IList<IEnumerator<T>> heads = new List<IEnumerator<T>>();

        foreach (IEnumerable<T> sourceSeq in source)
        {
            heads.Add(sourceSeq.GetEnumerator());
        }

        while (MoveAllHeads(heads, fillDefault))
        {
            yield return ReadHeads(heads);
        }
    }

    private static IEnumerable<T> ReadHeads<T>(IEnumerable<IEnumerator<T>> heads)
    {
        foreach (IEnumerator<T> head in heads)
        {
            if (head == null)
                yield return default(T);
            else
                yield return head.Current;
        }
    }

    private static bool MoveAllHeads<T>(IList<IEnumerator<T>> heads, bool fillDefault)
    {
        bool any = false;
        bool all = true;

        for (int i = 0; i < heads.Count; ++i)
        {
            bool hasNext = false;

            if(heads[i] != null) hasNext = heads[i].MoveNext();

            if (!hasNext) heads[i] = null;

            any |= hasNext;
            all &= hasNext;
        }

        if (any && !all && !fillDefault)
            throw new InvalidOperationException("Input sequences are of different length");

        return any;
    }
}
C-F
  • 1,597
  • 16
  • 25