Divide a large IEnumerable into smaller IEnumerable of a fix amount of item

前端 未结 5 519
忘了有多久
忘了有多久 2020-12-18 01:35

In order to support an API that only accepts a specific amount of items (5 items), I want to transform a LINQ result into smaller groups of items that always contain that se

5条回答
  •  囚心锁ツ
    2020-12-18 02:12

    var list = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
    var result = new List>();
    while (list.Count != 0) {
        result.Add(list.TakeWhile(x => x++ <= 5).ToList());
        list.RemoveRange(0, list.Count < 5 ? list.Count : 5);
    }
    

提交回复
热议问题