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

前端 未结 5 601
忘了有多久
忘了有多久 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:27

    One easy possibility is to use the Enumerable.Skip and Enumerable.Take methods, for example:

    List nums = new List(){1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
    
    var list1 = nums.Take(5);
    var list2 = nums.Skip(5).Take(5);
    var list3 = nums.Skip(10).Take(5);
    var list4 = nums.Skip(15).Take(5);
    

    As Jon mentioned in the comments though, a simple approach like this one will re-evaluate nums (in this example) each time, which will impact performance (depending on the size of the collection).

提交回复
热议问题