Monty’s Gush

The IEnumerable.Pairwise function in C#

Posted on: March 30, 2009

kick it on DotNetKicks.com

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:

2 Responses to "The IEnumerable.Pairwise function in C#"

Nice, keep up the good work Pete. Jools.

Thanks, I was about to write this myself when I found this post!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: