Create batches in linq

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

    You don't need to write any code. Use MoreLINQ Batch method, which batches the source sequence into sized buckets (MoreLINQ is available as a NuGet package you can install):

    int size = 10;
    var batches = sequence.Batch(size);
    

    Which is implemented as:

    public static IEnumerable> Batch(
                      this IEnumerable source, int size)
    {
        TSource[] bucket = null;
        var count = 0;
    
        foreach (var item in source)
        {
            if (bucket == null)
                bucket = new TSource[size];
    
            bucket[count++] = item;
            if (count != size)
                continue;
    
            yield return bucket;
    
            bucket = null;
            count = 0;
        }
    
        if (bucket != null && count > 0)
            yield return bucket.Take(count).ToArray();
    }
    

提交回复
热议问题