Created
August 5, 2013 19:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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