C# Extension to split IEnumerable into batches of n items

This code splits a list into a batches on n items. If list = (1,2,3,4,5,6,7,8,9,10) and n = 3 then the result is ((1,2,3),(4,5,6),(7,8,9),(10))
public static class Extensions
{
  public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> list, int batchSize)
  {
    int i = 0;
    return list.GroupBy(x => (i++ / batchSize)).ToList();
  }
}
[TestFixture]
public class TestExtensions
{
  [Test]
  public void TestBatch()
  {
    var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    var result = list.Batch(3).ToList();
    Assert.AreEqual(4, result.Count());
    Assert.AreEqual(3, result[0].Count());
    Assert.AreEqual(3, result[1].Count());
    Assert.AreEqual(3, result[2].Count());
    Assert.AreEqual(1, result[3].Count());
    result.ForEach(x=>Console.WriteLine(string.Join(",",x)));
  }
}

Comments

  1. I tried going into the Extensions manager to get any clues, and when I changed settings I got a pop up error message.chrome extension development

    ReplyDelete
  2. I feel this is among the such a lot vital info for me. And i am satisfied studying your article. However wanna commentary on few general things, The website style is ideal, the articles is truly nice
    Tangki Panel

    ReplyDelete
  3. Great Article IoT Projects for Students

    Deep Learning Projects for Final Year

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

C# Crop white space from around the image