Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a collection into `n` parts with LINQ? [duplicate]

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.

like image 962
Simon_Weaver Avatar asked Oct 02 '22 15:10

Simon_Weaver


1 Answers

A pure linq and the simplest solution is as shown below.

static class LinqExtensions
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
    {
        int i = 0;
        var splits = from item in list
                     group item by i++ % parts into part
                     select part.AsEnumerable();
        return splits;
    }
}
like image 132
Muhammad Hasan Khan Avatar answered Oct 18 '22 06:10

Muhammad Hasan Khan