LINQed IN

Blog by Troy Magennis on Software Architecture, Development and Management

About the author

Troy Magennis is a software developer living in Seattle, WA. Troy is a Microsoft MVP, the author of many articles, and the founder of HookedOnLINQ.com, a LINQ specific wiki reference site.
E-mail me Send mail

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Zip - New LINQ to Objects .NET 4.0 Operator

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.


Categories: C# | LINQ
Posted by t_magennis on Monday, January 05, 2009 5:56 AM
Permalink | Comments (0) | Post RSSRSS comment feed
Comments are closed