开发者

how to use linq on a list<T> to generate a list<lists<T>> in C#

开发者 https://www.devze.com 2023-01-11 20:15 出处:网络
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.

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. A开发者_运维问答nd 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}}


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消