LINQ gems: Zip

I'm always fascinated by how simple yet helpful LINQ queries are.

Take for example the Enumerable.Zip() method. It's simple, yet very useful in case you need to combine two sequences of data.

Here's a partial example where Zip() is used to combine a sequence of original text resources with their translations (produced for example by the Google Cloud Translation API):

public IEnumerable<(ResourceText text, string translation)> 
    TranslateResourceTexts(IEnumerable<ResourceText> resourceTexts)
{
    // Grab just the strings to translate
    IEnumerable<string> strings = resourceTexts.Select(t => t.Text);

    // Translate the strings (call Google Translate V3 API)
    IEnumerable<string> translatedStrings = TranslateStrings(strings);

    // Combine the two sequences, producing an enumerable of tuples 
    // containing both the original resource text and its translation
    return resourceTexts.Zip(translatedStrings, (text, translation) 
                             => (text, translation));
}

Simple and easily readable.

As with most of the LINQ functions, I could of course accomplish the same with a for or for each loop and a few extra lines of code. However, in most cases, I consider the use of LINQ syntax a cleaner alternative.

Final notes:

  • The Zip() method can only be called using the LINQ method syntax, there's no query syntax option for it.
  • It is available starting with .NET Framework 4.0.

Comments (1)

Kamen Dimitrov's photo

Pretty neat