C# List Batch – Breaking an IEnumerable into batches with .NET

There are several ways of batching lists and enumerables with C#. Here are 3 ways:

METHOD 1: USING MoreLINQ

MoreLINQ is an extension package for LINQ that implements yet another set of useful LINQ expressions like Shuffle, Pad, and Batch.

Get the MoreLINQ NuGet package here: https://www.nuget.org/packages/morelinq/

METHOD 2: BATHCING USING FOREACH AND YIELD

This implementation looks a lot like the one that MoreLINQ uses. It utilizes a foreach loop, building a new list that is then returned:

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyCode
{
  internal static class EnumerableExtension
  {
    public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> enumerator, int size)
    {
      T[] batch = null;
      var count = 0;

      foreach (var item in enumerator)
      {
        if (batch == null)
          batch = new T[size];

        batch[count++] = item;
        if (count != size)
          continue;

        yield return batch;

        batch = null;
        count = 0;
      }

      if (batch != null && count > 0)
        yield return batch.Take(count).ToArray();
    }
  }
}

METHOD 3: BATCHING USING SKIP() AND TAKE()

This method is a little shorter, and utilizes the Skip() to jump to the next batch, and Take() to grab the batch:

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyCode
{
  internal static class EnumerableExtension
  {
    public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> enumerator, int size)
    {
      var length = enumerator.Count();
      var pos = 0;
      do
      {
        yield return enumerator.Skip(pos).Take(size);
        pos = pos + size; 
      } while (pos < length);
    }
  }
}

HOW TO USE THE BATCH METHODS ABOVE:

You can try it out using this tiny sample:

public class Program
{
	public static void Main()
	{
		// Add 25 numbers to a list 
        List<int> list = new List<int>();
		for (int i=0;i<25;i++)
			list.Add(i);
        // Batch the list into batches of 7
        var batches = list.Batch(7);
		foreach (var batch in batches)
		{
			foreach (var item in batch)
				Console.Write(item + " ");
			Console.WriteLine(" batch end");	
		}			
	}
}

The code above will return the following output:

0 1 2 3 4 5 6  batch end
7 8 9 10 11 12 13  batch end
14 15 16 17 18 19 20  batch end
21 22 23 24  batch end

That’s it. You are now a C# expert. Happy coding.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.