Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active December 15, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/5200750 to your computer and use it in GitHub Desktop.
Save gsscoder/5200750 to your computer and use it in GitHub Desktop.
IEnumerable<T>::Pairwise extension method for C# modeled like an overload of F# Seq.pairwise<'T> (http://msdn.microsoft.com/it-it/library/ee370361.aspx).
public static IEnumerable<TResult> Pairwise<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TSource, TResult> selector)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (selector == null)
{
throw new ArgumentNullException("selector");
}
using (var enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
var left = enumerator.Current;
while (enumerator.MoveNext())
{
var right = enumerator.Current;
yield return selector(left, right);
left = right;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment