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.
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;
}
}
}

1 | IEnumerator.Next(count) « Monty’s Gush
April 11, 2010 at 2:43 pm
[...] IEnumerable.GroupsOf(n) The IEnumerable.Pairwise function [...]