Is there a nice way to split a collection into n
parts with LINQ?
Not necessarily evenly of course.
That is, I want to divide the collection into sub-collections, which each contains a subset of the elements, where the last collection can be ragged.
I have been using the Partition function I posted earlier quite often. The only bad thing about it was that is wasn't completely streaming. This is not a problem if you work with few elements in your sequence. I needed a new solution when i started working with 100.000+ elements in my sequence.
The following solution is a lot more complex (and more code!), but it is very efficient.
Enjoy!
I was looking for a split like the one with string, so the whole List is splitted according to some rule, not only the first part, this is my solution
Ok, I'll throw my hat in the ring. The advantages of my algorithm:
The code:
As pointed out in the comments below, this approach doesn't actually address the original question which asked for a fixed number of sections of approximately equal length. That said, you can still use my approach to solve the original question by calling it this way:
When used in this manner, the approach is no longer O(1) as the Count() operation is O(N).
This is same as the accepted answer, but a much simpler representation:
The above method splits an
IEnumerable<T>
into N number of chunks of equal sizes or close to equal sizes.The above method splits an
IEnumerable<T>
into chunks of desired fixed size with total number of chunks being unimportant - which is not what the question is about.The problem with the
Split
method, besides being slower, is that it scrambles the output in the sense that the grouping will be done on the basis of i'th multiple of N for each position, or in other words you don't get the chunks in the original order.Almost every answer here either doesn't preserve order, or is about partitioning and not splitting, or is plainly wrong. Try this which is faster, preserves order but a lil' more verbose:
The equivalent method for a
Partition
operation hereA pure linq and the simplest solution is as shown below.