When looking through the .NET 4.0 framework bits given out at the recent Microsoft PDC conference, I discovered a new operator - Zip
Zip combines the elements from two sequences, by making available the element at the same index position in each sequence. The sequence stops as soon as one of the sequences exhausts its elements; ideally, the sequences are identical in length. The merging happens in the func function. It takes two arguments (the element from foe first source, and the element from the second source) and lets you return a combined type.
The extension method signature is:
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> func);
Sample usage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ZipTest
{
class Program
{
static void Main(string[] args)
{
string[] s1 = new string[] { "a", "b", "c" };
int[] s2 = new int[] { 1, 2, 3 };
var q = s1.Zip(s2, (a, b) => a + b);
foreach (var e in q)
Console.WriteLine(e);
/* Output:
* a1
* b2
* c3
*
*/
}
}
}
Troy.