How do I merge (or zip) two IEnumerables together?

前端 未结 10 1615
予麋鹿
予麋鹿 2020-12-17 00:38

I have an IEnumerable and an IEnumerable that I want merged into an IEnumerable> where

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 01:01

    Another implementation from the functional-dotnet project by Alexey Romanov:

    /// 
    /// Takes two sequences and returns a sequence of corresponding pairs. 
    /// If one sequence is short, excess elements of the longer sequence are discarded.
    /// 
    /// The type of the 1.
    /// The type of the 2.
    /// The first sequence.
    /// The second sequence.
    /// 
    public static IEnumerable> Zip(
        this IEnumerable sequence1, IEnumerable sequence2) {
        using (
            IEnumerator enumerator1 = sequence1.GetEnumerator())
        using (
            IEnumerator enumerator2 = sequence2.GetEnumerator()) {
            while (enumerator1.MoveNext() && enumerator2.MoveNext()) {
                yield return
                    Pair.New(enumerator1.Current, enumerator2.Current);
            }
        }
        //
        //zip :: [a] -> [b] -> [(a,b)]
        //zip (a:as) (b:bs) = (a,b) : zip as bs
        //zip _      _      = []
    }
    

    Replace Pair.New with new KeyValuePair (and the return type) and you're good to go.

提交回复
热议问题