Skip to content

Instantly share code, notes, and snippets.

@rossmurray
Created August 5, 2013 19:16
Show Gist options
  • Save rossmurray/6158617 to your computer and use it in GitHub Desktop.
Save rossmurray/6158617 to your computer and use it in GitHub Desktop.
Returns an IEnumerable of paired input. {1,2,3,4} -> {(1,2), (2,3), (3,4)} Useful in doing things like computing intervals between input elements, while only doing a single pass over the input.
public static class ExtensionMethods
{
//given a list {1,2,3,4}, this will return {(1,2), (2,3), (3,4)}
public static IEnumerable<Tuple<T,T>> AsSlidingPairs<T>(this IEnumerable<T> list)
{
if(list == null) throw new ArgumentNullException();
if(!list.Any())
{
yield break;
}
var previousItem = list.First();
foreach(var currentItem in list.Skip(1))
{
yield return Tuple.Create(previousItem, currentItem);
previousItem = currentItem;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment