Split a List into smaller lists of N size

前端 未结 17 1784
后悔当初
后悔当初 2020-11-22 16:55

I am attempting to split a list into a series of smaller lists.

My Problem: My function to split lists doesn\'t split them into lists of the correct

17条回答
  •  长发绾君心
    2020-11-22 17:43

    Library MoreLinq have method called Batch

    List ids = new List() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // 10 elements
    int counter = 1;
    foreach(var batch in ids.Batch(2))
    {
        foreach(var eachId in batch)
        {
            Console.WriteLine("Batch: {0}, Id: {1}", counter, eachId);
        }
        counter++;
    }
    

    Result is

    Batch: 1, Id: 1
    Batch: 1, Id: 2
    Batch: 2, Id: 3
    Batch: 2, Id: 4
    Batch: 3, Id: 5
    Batch: 3, Id: 6
    Batch: 4, Id: 7
    Batch: 4, Id: 8
    Batch: 5, Id: 9
    Batch: 5, Id: 0
    

    ids are splitted into 5 chunks with 2 elements.

提交回复
热议问题