Isg.Collections Now Includes EachConsecutive().

This morning at #SCNA Michael Feathers (@mfeathers) showcased an interesting Ruby function each_cons(). At first glance I didn’t think the function was all that useful, but then he showed how you could use it to see if a list is sorted. I couldn’t find a .NET implementation anywhere, so I added it to my Isg.Collections NuGet package as EachConsecutive().

The algorithm relies on knowing the count of items in its source enumerable. This requires that the enumerable be materialzied. I didn’t want to create deferred execution on Enumerable, so the extension method operates on ICollection<T> instead of IEnumerable<T>.

Here’s some sample code:

// Arrange: Declare any variables or set up any conditions // required by your test. var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Act: Perform the activity under test. var isSorted = array.EachConsecutive()
    .All(pair =>
    {
        var left = pair.First();
        var right = pair.Last();
        return left < right;
    });

var isNotSorted = array
    .Reverse()
    .ToArray()
    .EachConsecutive()
    .All(pair =>
             {
                 var left = pair.First();
                 var right = pair.Last();
                 return left < right;
             });

// Assert: Verify that the activity under test had the // expected results Assert.That(isSorted, Is.True);
Assert.That(isNotSorted, Is.False);

Leave a Reply

%d bloggers like this: