Enumerable.Zip Dot Net 3.0 中的替代解决方案

Enumerable.Zip alternative solution in Dot Net 3.0

我想知道 Enumerable.Zip.

在 Dot Net 3.0 中是否有可用的替代解决方案

这是我要实现的示例:

我有两个字符串列表。

var list1 = new string[] { "1", "2", "3" };
var list2 = new string[] { "a", "b", "c" };

我想合并这些列表,这样 returns 输出如下:

{(1,a), (2,b), (3,c)}

我知道,我可以在 Dot Net >= 4.0 中使用 Zip 来做到这一点。使用方式:

list1.Zip(list2, (x, y) => new Tuple<int, string>(x, y));

但是,我的问题是我想在 Dot Net 3.0 中做同样的事情。 Dot Net <= 3.0 中是否有可用的替代方法,或者我必须创建自定义方法?

如您所知,它在 .NET 3.5 及更早版本中不可用。然而,Eric Lippert 在这里 https://blogs.msdn.microsoft.com/ericlippert/2009/05/07/zip-me-up/:

实现了它

The code to do so is pretty trivial; if you happen to need this in C# 3.0, I’ve put the source code below.

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
    (this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    if (first == null) throw new ArgumentNullException("first");
    if (second == null) throw new ArgumentNullException("second");
    if (resultSelector == null) throw new ArgumentNullException("resultSelector");
    return ZipIterator(first, second, resultSelector);
}

private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>
    (IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    using (IEnumerator<TFirst> e1 = first.GetEnumerator())
        using (IEnumerator<TSecond> e2 = second.GetEnumerator())
            while (e1.MoveNext() && e2.MoveNext())
                yield return resultSelector(e1.Current, e2.Current);
}