Create batches in linq

前端 未结 16 1873
傲寒
傲寒 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:32

    public static class MyExtensions
    {
        public static IEnumerable> Batch(this IEnumerable items,
                                                           int maxItems)
        {
            return items.Select((item, inx) => new { item, inx })
                        .GroupBy(x => x.inx / maxItems)
                        .Select(g => g.Select(x => x.item));
        }
    }
    

    and the usage would be:

    List list = new List() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    
    foreach(var batch in list.Batch(3))
    {
        Console.WriteLine(String.Join(",",batch));
    }
    

    OUTPUT:

    0,1,2
    3,4,5
    6,7,8
    9
    

提交回复
热议问题