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

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

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

相关标签:
10条回答
  • 2020-12-17 00:57

    As a update to anyone stumbling across this question, .Net 4.0 supports this natively as ex from MS:

    int[] numbers = { 1, 2, 3, 4 };
    string[] words = { "one", "two", "three" };
    
    var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
    
    0 讨论(0)
  • 2020-12-17 00:57

    JaredPar has a library with a lot of useful stuff in it, include Zip which will enable what you want to do.

    0 讨论(0)
  • 2020-12-17 01:00

    You could use the Zip methods in MoreLINQ.

    0 讨论(0)
  • 2020-12-17 01:01

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

    /// <summary>
    /// Takes two sequences and returns a sequence of corresponding pairs. 
    /// If one sequence is short, excess elements of the longer sequence are discarded.
    /// </summary>
    /// <typeparam name="T1">The type of the 1.</typeparam>
    /// <typeparam name="T2">The type of the 2.</typeparam>
    /// <param name="sequence1">The first sequence.</param>
    /// <param name="sequence2">The second sequence.</param>
    /// <returns></returns>
    public static IEnumerable<Tuple<T1, T2>> Zip<T1, T2>(
        this IEnumerable<T1> sequence1, IEnumerable<T2> sequence2) {
        using (
            IEnumerator<T1> enumerator1 = sequence1.GetEnumerator())
        using (
            IEnumerator<T2> 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<T1, T2> (and the return type) and you're good to go.

    0 讨论(0)
提交回复
热议问题