Skip to main content

Command Palette

Search for a command to run...

LINQ gems: Zip

Published
2 min read
LINQ gems: Zip
J

I'm an "old-school" Software Engineer, mostly specializing in C# and .NET.

Currently in the process of discovering AI and Machine Learning.

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.

If you find this post interesting, be sure to check out my other posts in the LINQ gems series.

874 views
K

Pretty neat

More from this blog

My Dev Tricks

12 posts

Trying to disprove that old-school Devs cannot learn new tricks!