How to do Python's zip in C#?

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);

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);
            }
        }
    }

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
        );
    }
}

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


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;
    }
}

Comments

  1. Titus

    • 2015/9/2

    , but it is also difficult to master. Anyone can learn Python if they work hard enough at it, but becoming a Python Developer will require a lot of practice and patience.

  2. Alfredo

    • 2021/4/16

    Installing Python is generally easy, and nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers (notably those from HP) now come with Python already installed. If you do need to install Python and aren't confident about the task you can find a few notes on the BeginnersGuide/Download wiki page, but

  3. Jeffrey

    • 2019/11/18

    The official home of the Python Programming Language. Whether you're new to programming or an experienced developer, it's easy to learn and use Python.

  4. Emmitt

    • 2019/11/13

    Running Your Python Interpreter. You can do a quick test to ensure Python is installed correctly. Fire up your terminal or command line and run the python3 command. That should open a Python interactive session, and your command prompt should look similar to this: >>>

  5. Sorrentino

    • 2017/10/31

    In this tutorial, you'll learn: What Python is and why you should use it; What basic Python syntax you should learn to start coding; How to 

  6. Jovanni

    • 2016/3/28

    Python Developer Meaning: What Does a Python Developer Do? The goal of a Python developer is to ensure full functionality in software. To accomplish this, they carry out several tasks on a regular basis, from testing and debugging to writing code. We take a closer look at the most common tasks below. Test and Debug Software

  7. Jayce

    • 2016/11/9

    I wanted to learn how to make websites using Python, but it seemed like every learning resource wanted me to spend two long, boring, 

  8. Victor

    • 2018/6/8

    But it can be difficult to build Python projects for beginners. Where do you start? What makes a good project? What do you do when you get stuck 

  9. Elisha

    • 2020/6/25

    Python is an interpreted language, and in order to run Python code, you must tell VS Code which interpreter to use. We recommend using the most 

  10. Esposito

    • 2020/10/15

    What is Python used for? · 1. AI and machine learning · 2. Data analytics · 3. Data visualisation · 4. Programming applications · 5. Web development.

Comments are closed.

Recent Posts