Create batches in linq

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

    Same approach as MoreLINQ, but using List instead of Array. I haven't done benchmarking, but readability matters more to some people:

        public static IEnumerable> Batch(this IEnumerable source, int size)
        {
            List batch = new List();
    
            foreach (var item in source)
            {
                batch.Add(item);
    
                if (batch.Count >= size)
                {
                    yield return batch;
                    batch.Clear();
                }
            }
    
            if (batch.Count > 0)
            {
                yield return batch;
            }
        }
    

提交回复
热议问题