Create batches in linq

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

    If you start with sequence defined as an IEnumerable, and you know that it can safely be enumerated multiple times (e.g. because it is an array or a list), you can just use this simple pattern to process the elements in batches:

    while (sequence.Any())
    {
        var batch = sequence.Take(10);
        sequence = sequence.Skip(10);
    
        // do whatever you need to do with each batch here
    }
    

提交回复
热议问题