The IEnumerable.Pairwise function in C#
Posted on: March 30, 2009
One handy function in the F# Seq module is Seq.pairwise.
[ 1 ; 2 ; 3 ; 4 ; 5] |> Seq.pairwise
It produces a sequence of, well, pairs:
val it : seq<int * int> = seq [(1, 2); (2, 3); (3, 4); (4, 5)]
Its main use is comparing each value in a sequence with its successor. One example might be analysing a web server log for suspicious crawlers.
Obviously you’ll need your own Pair class, which I’ll leave to you, reader (at least until we get tuples in .NET 4). No argument checking, but otherwise I think complete. Enjoy!
public static class EnumerableExtensions
{
/// <summary>
/// Returns a sequence of each element in the input sequence and its
/// predecessor, with the exception of the first element which is only
/// returned as the predecessor of the second element.
/// </summary>
public static IEnumerable<Pair<T, T>> Pairwise<T>(
this IEnumerable<T> source)
{
T previous = default(T);
using (var it = source.GetEnumerator())
{
// skip the first element
if (it.MoveNext())
previous = it.Current;
while (it.MoveNext())
{
yield return new Pair<T, T>
{
First = previous,
Second = it.Current
};
previous = it.Current;
}
}
}
}
Update .NET 4 introduced the Enumerable.Zip method into the framework which can be used to easily create a pairwise sequence in C#.
ts.Zip(us.Skip(1), (t, u) => new { t, u});
Tags: iterators
2 Responses to "The IEnumerable.Pairwise function in C#"
Thanks, I was about to write this myself when I found this post!
March 31, 2009 at 11:32 pm
Nice, keep up the good work Pete. Jools.