Is there any way I can separate a List<SomeObject>
into several separate lists of SomeObject
, using the item index as the delimiter of each split?
Let me exemplify:
I have a List<SomeObject>
and I need a List<List<SomeObject>>
or List<SomeObject>[]
, so that each of these resulting lists will contain a group of 3 items of the original list (sequentially).
eg.:
Original List:
[a, g, e, w, p, s, q, f, x, y, i, m, c]
Resulting lists:
[a, g, e], [w, p, s], [q, f, x], [y, i, m], [c]
I'd also need the resulting lists size to be a parameter of this function.
Another way is using Rx Buffer operator
completely lazy, no counting or copying:
For anyone interested in a packaged/maintained solution, the MoreLINQ library provides the
Batch
extension method which matches your requested behavior:The
Batch
implementation is similar to Cameron MacFarland's answer, with the addition of an overload for transforming the chunk/batch before returning, and performs quite well.I wrote a Clump extension method several years ago. Works great, and is the fastest implementation here. :P
We can improve @JaredPar's solution to do true lazy evaluation. We use a
GroupAdjacentBy
method that yields groups of consecutive elements with the same key:Because the groups are yielded one-by-one, this solution works efficiently with long or infinite sequences.
System.Interactive provides
Buffer()
for this purpose. Some quick testing shows performance is similar to Sam's solution.