Saturday, September 5, 2015

Splitting a Generic List into Multiple Chunks

Refer: http://www.chinhdo.com/20080515/chunking/

Splitting a Generic List into Multiple Chunks


public static List> BreakIntoChunks(List list, int chunkSize)
{
    if (chunkSize <= 0)
    {
        throw new ArgumentException("chunkSize must be greater than 0.");
    }

    List> retVal = new List>();

    while (list.Count > 0)
    {
        int count = list.Count > chunkSize ? chunkSize : list.Count;
        retVal.Add(list.GetRange(0, count));
        list.RemoveRange(0, count);
    }

    return retVal;
}

No comments:

Post a Comment