Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - elegant way of partitioning a list?

I'd like to partition a list into a list of lists, by specifying the number of elements in each partition.

For instance, suppose I have the list {1, 2, ... 11}, and would like to partition it such that each set has 4 elements, with the last set filling as many elements as it can. The resulting partition would look like {{1..4}, {5..8}, {9..11}}

What would be an elegant way of writing this?

like image 292
David Hodgson Avatar asked Sep 08 '09 20:09

David Hodgson


1 Answers

Here is an extension method that will do what you want:

public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size) {     for (int i = 0; i < (source.Count / size) + (source.Count % size > 0 ? 1 : 0); i++)         yield return new List<T>(source.Skip(size * i).Take(size)); } 

Edit: Here is a much cleaner version of the function:

public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size) {     for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)         yield return new List<T>(source.Skip(size * i).Take(size)); } 
like image 150
Andrew Hare Avatar answered Oct 02 '22 19:10

Andrew Hare