EnumerableUtility.SplitIntoBins<T> method

Splits the source sequence into binCount equal-sized bins. If binCount does not evenly divide the total element count, then the first (total count % binCount) bins will have one more element than the following bins.

public static IEnumerable<ReadOnlyCollection<T>> SplitIntoBins<T>(this IEnumerable<T> source, 
    int binCount)
parameter description
source The sequence to split.
binCount The desired number of bins.

Return Value

A sequence of sub-sequences of the original sequence.

Remarks

WARNING: Calls Enumerable.Count(), which may enumerate the underlying sequence (if it is not an ICollection or array type). To avoid this, you may want to call EnumerateBatches instead, although that method saves all “uneveness” to the last batch, where as this one distributes it. For example, a 12-item sequence split into 5 bins will yield batches of (3, 3, 2, 2, 2); EnumerateBatches can give us (3, 3, 3, 3) or (2, 2, 2, 2, 2, 2), but cannot give us exactly 5 batches.

See Also