BHoM_Engine icon indicating copy to clipboard operation
BHoM_Engine copied to clipboard

Add a method for splitting a collection into chunks of even length

Open vietle-bh opened this issue 3 years ago • 1 comments
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 avatar Sep 01 '22 09:09 vietle-bh

@vietle-bh what's wrong with these methods: https://github.com/BHoM/BHoM_Engine/blob/main/Data_Engine/Query/ChunkBy.cs

FraserGreenroyd avatar Sep 01 '22 11:09 FraserGreenroyd

@FraserGreenroyd @vietle-bh is this issue still relevant? Can @desaiwangBH take a look at this?

travispotterBH avatar Jun 06 '23 19:06 travispotterBH

@travispotterBH , I've changed to using the methods Fraser mentioned in his comment, so closing this now.

vietle-bh avatar Jun 07 '23 13:06 vietle-bh