Monty’s Gush

IEnumerable.GroupsOf(n)

Posted on: April 1, 2009

A generic function to group a sequence into sequences of equal size.

var numbers = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

var groups = numbers.GroupsOf(3);

Now groups is a sequence of sequences containing three items.

Groups of 3

Perhaps you might use this in some tricky UI scenario or to gamble away your integers. You’ll need the IEnumerator.Next extension too.

Is this a special case of a more general function, I wonder?

/// <summary>
/// Groups a sequence into sequences of the specified size.
/// The final group may be shorter if there are leftover
/// elements.
/// </summary>
/// <param name="count">The size of the groups.</param>
public static IEnumerable<IEnumerable<T>> GroupsOf<T>(
    this IEnumerable<T> source,
    int count)
{
    using (var it = source.GetEnumerator())
    {
        while (true)
        {
            var group = it.Next(count).ToList();

            if (group.Any())
                yield return group;
            else
                break;
        }
    }
}

2 Responses to "IEnumerable.GroupsOf(n)"

[…] IEnumerable.GroupsOf(n) The IEnumerable.Pairwise function […]

[…] IEnumerable.GroupsOf(n) […]

Leave a comment