tags:

views:

458

answers:

2

Hi,

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!

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

Am I missing something?

idursun
No but I obviously am. I need more sleep. Thanks much!!!
RBear
Being pedantic - Enumerable.Range(1, 100) since he wanted to start at 1.
Winston Smith
+2  A: 

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);
Scott Ivey
Thanks also, but where does index come from?
RBear
i was hoping the select would project its index into the query. Looks like it doesn't. I'll update the example accordingly - so that you can use it with non-int based collections.
Scott Ivey
FYI, in the next version of the framework there will be a "zip join" extension method. If you zip a query result with an infinite sequence of integers, you get an indexed sequence. See my recent blog article on this subject for details.
Eric Lippert
nice - i'll definitely be looking forward to that feature.
Scott Ivey
@eric - thanks, im gonna try that out. Is that faster than using the select with index into a new type?
RBear