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

前端 未结 10 1612
予麋鹿
予麋鹿 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:51

    Note: As of .NET 4.0, the framework includes a .Zip extension method on IEnumerable, documented here. The following is maintained for posterity and for use in .NET framework version earlier than 4.0.

    I use these extension methods:

    // From http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx
    public static IEnumerable Zip(this IEnumerable first, IEnumerable second, Func func) {
        if (first == null) 
            throw new ArgumentNullException("first");
        if (second == null) 
            throw new ArgumentNullException("second");
        if (func == null)
            throw new ArgumentNullException("func");
        using (var ie1 = first.GetEnumerator())
        using (var ie2 = second.GetEnumerator())
            while (ie1.MoveNext() && ie2.MoveNext())
                yield return func(ie1.Current, ie2.Current);
    }
    
    public static IEnumerable> Zip(this IEnumerable first, IEnumerable second) {
        return first.Zip(second, (f, s) => new KeyValuePair(f, s));
    }
    

    EDIT: after the comments I'm obliged to clarify and fix some things:

    • I originally took the first Zip implementation verbatim from Bart De Smet's blog
    • Added enumerator disposing (which was also noted on Bart's original post)
    • Added null parameter checking (also discussed in Bart's post)

提交回复
热议问题