How to split a list into evenly sized chunks in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class SplitListIntoChunks_CSharp
{
    static void Main()
    {
        var aList = new List<int>();
        for (int i = 0; i < 31; i++) {
            aList.Add(i);
        }

        var result = Split(aList, 4);
        foreach (var chunk in result) {
            Console.WriteLine($"[{string.Join(", ", chunk)}]");
        }
    }

    static IEnumerable<List<T>> Split<T>(List<T> theList, int chunk)
    {
        // yield return - provide the next value in iteration
        for (int i = 0; i < theList.Count; i += chunk) {
            yield return theList.GetRange(i, Math.Min(chunk, theList.Count - i));
        }
    }
}

  
  
/*
  
run:
  
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20, 21, 22, 23]
[24, 25, 26, 27]
[28, 29, 30]
 
*/

 



answered Nov 12, 2024 by avibootz

Related questions

1 answer 132 views
9 answers 872 views
1 answer 116 views
2 answers 153 views
1 answer 120 views
1 answer 126 views
...