How to use Linq to group every N number of rows

后端 未结 3 682
自闭症患者
自闭症患者 2020-11-30 07:31

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

相关标签:
3条回答
  • 2020-11-30 08:05
    var q = Enumerable.Range(0, 100).GroupBy(x => x/3);
    

    Am I missing something?

    0 讨论(0)
  • 2020-11-30 08:05

    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);
    
    0 讨论(0)
  • 2020-11-30 08:20

    How about a simpler approach:

    var index = 0;
    var grpOf3s = students.GroupBy(x => index++ / 3);
    

    Update: If you are using the Key value of the group item then you will need to convert the group enumerable to a list. Otherwise you will get a different Key every time it is accessed.

    var index = 0;
    var grpOf3s = students.GroupBy(x => index++ / 3).ToList();
    
    0 讨论(0)
提交回复
热议问题