Monty’s Gush


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;

2 Responses to "IEnumerable.GroupsOf(n)"

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

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

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: