Create batches in linq

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

    An easy version to use and understand.

        public static List> chunkList(List listToChunk, int batchSize)
        {
            List> batches = new List>();
    
            if (listToChunk.Count == 0) return batches;
    
            bool moreRecords = true;
            int fromRecord = 0;
            int countRange = 0;
            if (listToChunk.Count >= batchSize)
            {
                countRange = batchSize;
            }
            else
            {
                countRange = listToChunk.Count;
            }
    
            while (moreRecords)
            {
                List batch = listToChunk.GetRange(fromRecord, countRange);
                batches.Add(batch);
    
                if ((fromRecord + batchSize) >= listToChunk.Count)
                {
                    moreRecords = false;
                }
    
                fromRecord = fromRecord + batch.Count;
    
                if ((fromRecord + batchSize) > listToChunk.Count)
                {
                    countRange = listToChunk.Count - fromRecord;
                }
                else
                {
                    countRange = batchSize;
                }
            }
            return batches;
        }
    

提交回复
热议问题