.Net Tips – Use LINQ to create pairs of adjacent elements from a collection

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

The real-time data platform that empowers developers to build innovative products faster and more reliably than ever before.

Learn more

Suppose you have an array of numbers, say, [1, 3, 5, 7, 9, …], and you want to pair each element up with its neighbour in the array, e.g. [[1, 3], [3, 5], [5, 7], [7, 9], …].

Sure, you can iterate through the indices of the elements and recursively grab the element at an index and its neighbour:

   1: // an array of odd numbers

   2: var arr = new[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };

   3:

   4: // standard imperative way, iterate through the indices and grab

   5: // the elements from the arrays

   6: var arrPairs = new List<int[]>();

   7: for (var i = 0; i < arr.Length - 1; i++)

   8: {

   9:     arrPairs.Add(new[] { arr[i], arr[i+1] });

  10: }

OR, you can use LINQ and the Zip method added in .Net 4 and do this instead:

   1: var arrPairsLinq = arr.Skip(1).Zip(arr, (second, first) => new[] { first, second }).ToArray();

A much more elegant solution, no? ;-)

Whenever you’re ready, here are 4 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  4. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

2 thoughts on “.Net Tips – Use LINQ to create pairs of adjacent elements from a collection”

Leave a Comment

Your email address will not be published. Required fields are marked *