2010-05-11 56 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