Create batches in linq

前端 未结 16 1876
傲寒
傲寒 2020-11-22 02:50

Can someone suggest a way to create batches of a certain size in linq?

Ideally I want to be able to perform operations in chunks of some configurable amount.

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:37

    Just another one line implementation. It works even with an empty list, in this case you get a zero size batches collection.

    var aList = Enumerable.Range(1, 100).ToList(); //a given list
    var size = 9; //the wanted batch size
    //number of batches are: (aList.Count() + size - 1) / size;
    
    var batches = Enumerable.Range(0, (aList.Count() + size - 1) / size).Select(i => aList.GetRange( i * size, Math.Min(size, aList.Count() - i * size)));
    
    Assert.True(batches.Count() == 12);
    Assert.AreEqual(batches.ToList().ElementAt(0), new List() { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    Assert.AreEqual(batches.ToList().ElementAt(1), new List() { 10, 11, 12, 13, 14, 15, 16, 17, 18 });
    Assert.AreEqual(batches.ToList().ElementAt(11), new List() { 100 });
    

提交回复
热议问题