Skip to content

Instantly share code, notes, and snippets.

@stakx
Created October 18, 2014 18:39
Show Gist options
  • Save stakx/a28717cf904876ed942f to your computer and use it in GitHub Desktop.
Save stakx/a28717cf904876ed942f to your computer and use it in GitHub Desktop.
LINQ operator that maps over adjacent items in the source sequence using the given selector function
static IEnumerable<R> Pairwise<T, R>(this IEnumerable<T> xs, Func<T, T, R> selector)
{
using (var enumerator = xs.GetEnumerator())
{
if (enumerator.MoveNext())
{
T x = enumerator.Current;
while (enumerator.MoveNext())
{
T y = enumerator.Current;
yield return selector(x, y);
x = y;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment