Python's zip
function does the following:
a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
result
[[1, 6], [2, 7], [3, 8]]
Python's zip
function does the following:
a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
result
[[1, 6], [2, 7], [3, 8]]
Solution 1:
IEnumerable<KeyValuePair<T1, T2>> Zip<T1, T2>(
IEnumerable<T1> a, IEnumerable<T2> b)
{
var enumeratorA = a.GetEnumerator();
var enumeratorB = b.GetEnumerator();
while (enumeratorA.MoveNext())
{
enumeratorB.MoveNext();
yield return new KeyValuePair<T1, T2>
(
enumeratorA.Current,
enumeratorB.Current
);
}
}
How about this?
C# 4.0 LINQ'S NEW ZIP OPERATOR
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> func);
Solution 2: Similar to C# 4.0 Zip, but you can use it in C# 3.0
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> func)
{
using(var enumeratorA = first.GetEnumerator())
using(var enumeratorB = second.GetEnumerator())
{
while (enumeratorA.MoveNext())
{
enumeratorB.MoveNext();
yield return func(enumeratorA.Current, enumeratorB.Current);
}
}
}
Also take a look at Cadenza which has all sorts of nifty utility methods.
Specifically look at the Zip extension methods here: http://gitorious.org/cadenza/cadenza/blobs/master/src/Cadenza/Cadenza.Collections/Enumerable.cs#line1303