2010-05-11 98 views
5

在其他语言(红宝石,蟒蛇,...)我可以使用zip(list1, list2)它是这样工作的:Linq/.NET3.5是否支持'zip'方法?

如果list1 is {1,2,3,4}list2 is {a,b,c}

然后zip(list1, list2)将返回:{(1,a), (2,b), (3,c), (d,null)}

就是这样可用的方法在.NET的Linq扩展中?

回答

12

.NET 4给了我们一个Zip方法,但它在.NET 3.5中不可用。如果你很好奇,Eric Lippert provides an implementation of Zip,你可能会觉得有用。

+0

回答下面一个实现确实 – katbyte 2014-01-09 06:38:16

+0

@Steven:不,这不:http://referencesource.microsoft.com/#System.Core/ System/Linq/Enumerable.cs,2b8d0f02389aab71 – Heinzi 2018-01-29 14:42:50

0

这两个实现都不会填写缺少的值(或者检查长度是否相同)。

这里是可以实现:

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector, bool checkLengths = true, bool fillMissing = false) { 
     if (first == null) { throw new ArgumentNullException("first");} 
     if (second == null) { throw new ArgumentNullException("second");} 
     if (selector == null) { throw new ArgumentNullException("selector");} 

     using (IEnumerator<TFirst> e1 = first.GetEnumerator()) { 
      using (IEnumerator<TSecond> e2 = second.GetEnumerator()) { 
       while (true) { 
        bool more1 = e1.MoveNext(); 
        bool more2 = e2.MoveNext(); 

        if(! more1 || ! more2) { //one finished 
         if(checkLengths && ! fillMissing && (more1 || more2)) { //checking length && not filling in missing values && ones not finished 
          throw new Exception("Enumerables have different lengths (" + (more1 ? "first" : "second") +" is longer)"); 
         } 

         //fill in missing values with default(Tx) if asked too 
         if (fillMissing) { 
          if (more1) { 
           while (e1.MoveNext()) { 
            yield return selector(e1.Current, default(TSecond));   
           } 
          } else { 
           while (e2.MoveNext()) { 
            yield return selector(default(TFirst), e2.Current);   
           } 
          } 
         } 

         yield break; 
        } 

        yield return selector(e1.Current, e2.Current); 
       } 
      } 
     } 
    } 
+0

+1,用于注意“缺失值”行为。但是,这是我的一个错误 - 它看起来像[Python的'zip'函数](http://docs.python.org/2/library/functions.html#zip)*也*停止时达到它的*最短*参数,就像Linq版本一样。 (并且我的假设 - 在问题中显示 - 是错误的) – 2014-01-09 08:59:06

+0

zip函数很奇怪,因此它默认为不是。但是我有几种情况是可取的。 – katbyte 2014-01-09 21:52:57

相关问题