Thursday, April 16, 2020

IEnumerable Batch Extension

Batches the given source into multiple provided size batches.
As we are dealing with IEnumerable and not IList therefore, we need to set the max batches that needs to be created.


 public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, uint size, uint max = byte.MaxValue)
        {
            var enumerator = source?.GetEnumerator();

            if (enumerator == null)
                yield break;

            IEnumerable CreateBatch()
            {
                var batch = size;
                while (batch-- > 0 && enumerator.MoveNext())
                {
                    yield return enumerator.Current;
                }
            }

            while (max-- > 0)
            {
                yield return CreateBatch();
            }
        }


Usage


var batches = GetIEnumerable().Batch(500, 50);