Friday, December 30, 2011

Segmenting IEnumerable into equal-sized chunks

A while ago, I found myself submitting data to a server, but the data needed to be chunked before being submitted; the reason for this was that server only allowed approximately 50 values to be submitted at a time.  The data was in a class inheriting from IEnumerable, so I figured why not write a simple extension method to segment data.  Easy peasy, but useful if needed.

public static class Extensions
{
    public static IEnumerable<IEnumerable<T>> Segment<T>(this IEnumerable<T> data, int segmentSize)
    {
        double dataSize = data.Count();
        var segmentCount = segmentSize == 0 ? 0 : (int)Math.Ceiling(dataSize / segmentSize);
        return Enumerable.Range(0, segmentCount).Select(i => data.Skip(i * segmentSize).Take(segmentSize));
    }
}

Using the extension method is as easy as:

var segments = Enumerable.Range(1, 10).Segment(3);

The results of running the above code is as follows:


Probably not the best solution since it does iterate over the collection multiple times, but it gets the job done.  Enjoy.

No comments:

Post a Comment