0 Comments Posted in:

Today in our journey through MoreLINQ we're looking at Pairwise, which is one of my favourites. In one sense, it's no more than a special case of Window which we looked at yesterday, with a window size of 2.

But Pairwise turns out to be a common requirement for all kinds of problems. For example, in the first Advent of Code challenge I needed pairwise on day 5, day 9, day 11 and day 13.

The use case I demonstrate in the video is from my first lunchtime LINQ challenge where you are given the times at which a swimmer completes each length of the pool. You need to turn this into a sequence of the times taken to swim each length.

The Pairwise extension method is ideally suited for this problem, and I also use the Prepend method to add an initial time onto the beginning of the sequence. However, this introduces a problem. Prepend has been a MoreLINQ extension method for some time, but has now been included in the .NET Framework (introduced in .NET 4.7.1).

This results in an ambiguity between extension methods and if you attempt to use an ambiguous extension method, your code will not compile unless you remove one of the using statements. So for example:

using System.Linq;
using MoreLinq;

// will not compile in .NET 4.7.1 and greater...
var diffs = data.Prepend(0).Pairwise((a,b) => b-a); 

The solution is to use some additional namespaces that MoreLINQ have provided. You keep the System.Linq namespace, but for every MoreLINQ extension method you want to use, you have to add a using static pointing at a special extension namespace that just provides that single method. So for example, this will now compile:

using System.Linq;
using static MoreLinq.Extensions.PairwiseExtension;

// uses Prepend from System.Linq
var diffs = data.Prepend(0).Pairwise((a,b) => b-a); 

It's a little cumbersome if you need to use several MoreLINQ extension methods as you'll need a using static for each one, but it is a way to work around the issue and allow you to use ambiguous methods.

You can find all videos in this series here.

Want to learn more about LINQ? Be sure to check out my Pluralsight course More Effective LINQ.
Vote on HN