C# - elegant way of partitioning a list?

前端 未结 11 697
情歌与酒
情歌与酒 2020-12-01 04:36

I\'d like to partition a list into a list of lists, by specifying the number of elements in each partition.

For instance, suppose I have the list {1, 2, ... 11}, and

11条回答
  •  粉色の甜心
    2020-12-01 05:13

    Using ArraySegments might be a readable and short solution (casting your list to array is required):

    var list = new List() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; //Added 0 in front on purpose in order to enhance simplicity.
    int[] array = list.ToArray();
    int step = 4;
    List listSegments = new List();
    
    for(int i = 0; i < array.Length; i+=step)
    {
         int[] segment = new ArraySegment(array, i, step).ToArray();
         listSegments.Add(segment);
    }
    

提交回复
热议问题