Skip to content

IEnumerable should have a extension for creating fixed size chunks #27449

Description

@inputfalken

Background and Motivation

There's currently no method available to create chunks from an IEnumerable<T>. It's a popular functionality as this comment shows.
I believe most projects in need of this functionality have their own extension to IEnumerable<T> and the goal of this proposal is to have System.Linq offer this functionality

Proposed API

namespace System.Linq
{
    public static class Enumerable
    {
+        public static IEnumerable<T[]> Chunk(this IEnumerable<T> source, int size);
    }

    public static class Queryable
    {
+        public static IQueryable<T[]> Chunk(this IQueryable<T> source, int size);
    }
}

Usage Examples

int[] numbers = new int[]{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9, 10, 11, 12}
IEnumerable<int[]> numberChunks = numbers.Chunk(5) // {[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]}

Alternative Designs

Another way to create chunks would be to specify the amount of chunks you would like to have from an IEnumerable<T> but I think it would be more desirable to have it as a separate method.
like the sample below.

// Where size determines the split amount.
public static IEnumerable<T[]> SplitBy(this IEnumerable<T> source, int size)
{
    ...
}

int[] numbers = new int[]{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9, 10}
IEnumerable<int[]> numberChunks = numbers.SplitBy(2) // {[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]}

Risks

This could potentially be a breaking change for users who have their own extension methods due to naming collisions.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Linqhelp wanted[up-for-grabs] Good issue for external contributors

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions