views:

101

answers:

1

I've seen examples of the reverse question, but they don't help me with this direction.

I've got a List where T has an int weight. I'd like to divide this into lists of 5 grouped by weight.
if I have the following T's with respective weights
A:1
B:2
C:3
D:4
E:5
F:6
G:7
H:8
I:9
J:-11
I want {A,B,C,D,E,F,G,H,I,J} to be sorted to {{J,A,B,C,D},{E,F,G,H,I}}
I'm not worried about cases where the number of items in the list isn't divisible by 5. And I'm not worried about the inners of the lists being sorted. For example I'd be happy with {{J,A,B,C,D},{F,I,G,H,E}} or even{{F,I,G,H,E},{J,A,B,C,D}}

+3  A: 
var query = data.OrderBy(x => x.Weight)
                .Select((x, i) => new { Value = x, Group = i / 5 })
                .GroupBy(x => x.Group, x => x.Value, (k, g) => g.ToList())
                .ToList();

If you're happy with query being typed as simply IEnumerable<IEnumerable<T>> rather than List<List<T>> then you could leave out the ToList calls altogether:

var query = data.OrderBy(x => x.Weight)
                .Select((x, i) => new { Value = x, Group = i / 5 })
                .GroupBy(x => x.Group, x => x.Value);
LukeH
I like the `i / 5` trick — but I would really strongly recommend to put a comment above this line of code that explains it, otherwise it is too unobvious to readers of the code.
Timwi