Skip to content

Instantly share code, notes, and snippets.

@pmunin
Last active September 19, 2020 02:29
Show Gist options
  • Select an option

  • Save pmunin/533c10f0020b21230177cfb5a2d75bb4 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

Unfortunately, this crashes with an overflow error when the list is 14526 long with a size param of 100.

@pmunin
Copy link
Copy Markdown
Author

pmunin commented Sep 18, 2020

Unfortunately, this crashes with an overflow error when the list is 14526 long with a size param of 100.

thanks for catching it - I fixed it - try now.

@ketchup201
Copy link
Copy Markdown

Works great, thanks for the quick turnaround!!

@pmunin
Copy link
Copy Markdown
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