Last active
December 15, 2015 04:19
-
-
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).
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 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