【问题标题】:Enumerable.Zip alternative solution in Dot Net 3.0Dot Net 3.0 中的 Enumerable.Zip 替代解决方案
【发布时间】:2018-04-19 23:27:13
【问题描述】:

我想知道在 Dot Net 3.0 中对于Enumerable.Zip 是否有任何替代解决方案。

这是我要实现的示例:

我有两个字符串列表。

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

我想组合这些列表,以这样的方式返回输出:

{(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

【问题讨论】:

标签: c# .net linq .net-3.0


【解决方案1】:

如您所知,它在 .NET 3.5 和旧版本中不可用。然而,Eric Lippert 在这里https://blogs.msdn.microsoft.com/ericlippert/2009/05/07/zip-me-up/ 有一个实现:

这样做的代码非常简单;如果你碰巧在 C# 3.0 中需要这个,我把源代码放在下面。

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

【讨论】:

  • @PatrickHofman 这是有道理的。博客文章说它是从 .NET 4 复制而来的:“在 C# 4.0 附带的基类库版本中,我们将在标准扩展方法中添加一个 Zip 序列运算符。要执行的代码所以很简单;如果你碰巧在 C# 3.0 中需要这个,我把源代码放在下面。[...] 这里是源代码:"
  • .NET 3 中没有Func。我尝试构建一个基本版本here
  • .NET 3 中也没有扩展(默认情况下)。除此之外,这不是Enumerable.Zip的正常实现吗? referencesource.microsoft.com/#System.Core/System/Linq/…
  • 谢谢大家!
猜你喜欢
  • 1970-01-01
  • 2011-04-13
  • 2016-10-24
  • 2020-08-29
  • 2011-07-09
  • 1970-01-01
  • 2018-02-07
  • 2016-04-30
  • 2017-08-27
相关资源
最近更新 更多