Last active
September 19, 2020 02:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Works great, thanks for the quick turnaround!!
Glad it works!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for catching it - I fixed it - try now.