LINQ gems: Zip

I'm an "old-school" Software Engineer, mostly specializing in C# and .NET.
Currently in the process of discovering AI and Machine Learning.
Search for a command to run...

I'm an "old-school" Software Engineer, mostly specializing in C# and .NET.
Currently in the process of discovering AI and Machine Learning.
Pretty neat
Since the inception of LINQ, methods suffixed with 'By' have played an important role in simplifying LINQ operations by introducing an additional 'selector' parameter. A typical example is the OrderBy method. Without the selector parameter, even a st...

One key reason I find myself drawn to social media is its power to inspire through the diverse perspectives of people. People tweeting or blogging about stuff they do or like, youtube videos and podcasts on different topics, all of these embed little...

Whether you're a seasoned Microsoft tech stack developer or just starting out, this tutorial is the ideal place to begin your Python journey. And, to sweeten things up a little bit, you're going to use ChatGPT to help you get started! Without further...

In line with the title of this blog, I'd like to start posting articles about languages, tools and technologies that I got a chance to use recently. One of the technologies that I was lucky to learn is PostgreSQL. I have always been an avid Microsoft...

Shakespeare will hopefully forgive me for abusing a line from his famous Hamlet. In my post, I won't be covering questions of life and death, but rather something much more prosaic - a lesser-known LINQ materialization method - ToLookup. We all know ...

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:
If you find this post interesting, be sure to check out my other posts in the LINQ gems series.