Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Linq to group every N number of rows

Tags:

c#

linq

group-by

I cannot find a way to make this work and hoping someone has an idea. A simplified example would be having a list of say integers 1-100, i want to group every 3 rows so the result would be 1,2,3 in first group then 4,5,6 in next group etc. I know how to get every nth record but what I need is all the records so I can then aggregate them, using first, last, sum, max, etc.

Thanks!

like image 429
RBear Avatar asked May 13 '09 20:05

RBear


2 Answers

This example should work for querying non-numeric collections. It projects an index into the object to be grouped, and then removes it again during the grouping.

var studentQuery2 = students
    .Select((student, index) => new {student, index})
    .GroupBy(g => g.index / 3, i => i.student);
like image 173
Scott Ivey Avatar answered Oct 22 '22 19:10

Scott Ivey


var q = Enumerable.Range(0, 100).GroupBy(x => x/3);

Am I missing something?

like image 31
idursun Avatar answered Oct 22 '22 20:10

idursun