Skip to content

Instantly share code, notes, and snippets.

@benjamin-bader
Created April 22, 2012 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamin-bader/2467380 to your computer and use it in GitHub Desktop.
Save benjamin-bader/2467380 to your computer and use it in GitHub Desktop.
Partition Operator
public static IEnumerable<IList<T>> Partition<T>(this IEnumerable<T> collection, int windowSize)
{
if (collection == null)
throw new ArgumentNullException("collection");
List<T> list;
using (var enumerator = collection.GetEnumerator())
{
// Break on an empty sequence to avoid a pointless allocation.
if (!enumerator.MoveNext())
yield break;
list = new List<T>(windowSize);
do
{
list.Add(enumerator.Current);
if (list.Count == windowSize)
{
yield return list;
list = new List<T>(windowSize);
}
}
while (enumerator.MoveNext());
}
if (list.Count != 0)
{
yield return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment