Quantcast
Channel: C# 4 – theburningmonk.com
Viewing all articles
Browse latest Browse all 10

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

$
0
0

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? ;-)

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.

Hi, my name is Yan Cui. I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

You can contact me via Email, Twitter and LinkedIn.

Hire me.

The post .Net Tips – Use LINQ to create pairs of adjacent elements from a collection appeared first on theburningmonk.com.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles



Latest Images