Skip to content

Instantly share code, notes, and snippets.

@pmunin
Last active September 19, 2020 02:29
Show Gist options
  • Save pmunin/533c10f0020b21230177cfb5a2d75bb4 to your computer and use it in GitHub Desktop.
Save pmunin/533c10f0020b21230177cfb5a2d75bb4 to your computer and use it in GitHub Desktop.
C# Enumerable extension for Partitioning also know as Pagination- allows to split enumerable into partitions of specified max size
using System.Linq;
public static class EnumerablePartitionExtensions{
/// <summary>
/// Generate lazy partitions for enumerable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items">source items to create partitions from</param>
/// <param name="size">max size of each partition</param>
/// <returns></returns>
public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> items, int size)
{
using (var enumerator = items.GetEnumerator())
{
bool hasNext = enumerator.MoveNext();
IEnumerable<T> nextPartitionOf()
{
var remainingCountForPartition = size;
while (remainingCountForPartition-- > 0 && hasNext)
{
yield return enumerator.Current;
hasNext = enumerator.MoveNext();
}
}
while (hasNext)
yield return nextPartitionOf().ToArray();
}
}
}
@ketchup201
Copy link

Works great, thanks for the quick turnaround!!

@pmunin
Copy link
Author

pmunin commented Sep 19, 2020

Glad it works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment