BHoM_Engine
BHoM_Engine copied to clipboard
Add a method for splitting a collection into chunks of even length
trafficstars
Description:
We need a method for splitting a collection into chunks of even length. Something along the line of:
[Description("Split an IEnumerable/ICollection into sub enumerables/collections of equal length.")]
[Input("source", "The IEnumerable/ICollection to be split into chunks.")]
[Input("chunksize", "The required number of items in each enumerable/collection resulted from the split.")]
[Output("IEnumerable", "A collection of enumerables/collections of equal length.")]
public static IEnumerable<IEnumerable<T>> SplitCollection<T>(this IEnumerable<T> source, int chunksize)
{
if (chunksize <= 0 || source == null)
yield break;
while (source.Any())
{
// Using ToList() to avoid deferred execution issues
yield return source.Take(chunksize).ToList();
source = source.Skip(chunksize);
}
}
@vietle-bh what's wrong with these methods: https://github.com/BHoM/BHoM_Engine/blob/main/Data_Engine/Query/ChunkBy.cs
@FraserGreenroyd @vietle-bh is this issue still relevant? Can @desaiwangBH take a look at this?
@travispotterBH , I've changed to using the methods Fraser mentioned in his comment, so closing this now.