Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use linq to break up list<t> into lots of list<t> of n length? [duplicate]

Tags:

Possible Duplicate:
How can I split an IEnumerable<String> into groups of IEnumerable<string>

I have a list that I would like to break into groups of 10.

If I have an object

List<Person> allPendingPersons  

that is of length m.

Is there an elegant way in LINQ to break up allPendingPersons into one or more List objects that all have a up to 10 Persons?

like image 619
Diskdrive Avatar asked Mar 07 '11 03:03

Diskdrive


1 Answers

You can write your own extension method:

public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> sequence, int size) {     List<T> partition = new List<T>(size);     foreach(var item in sequence) {         partition.Add(item);         if (partition.Count == size) {             yield return partition;             partition = new List<T>(size);         }     }     if (partition.Count > 0)         yield return partition; } 

I explored this in more depth in my blog.

like image 93
SLaks Avatar answered Nov 24 '22 10:11

SLaks