Return to Snippet

Revision: 57165
at May 18, 2012 19:05 by witmann


Initial Code
public static List<T>[] Partition<T>(List<T> list, int totalPartitions)
{
    if (list == null)
        throw new ArgumentNullException("list");

    if (totalPartitions < 1)
        throw new ArgumentOutOfRangeException("totalPartitions");

    List<T>[] partitions = new List<T>[totalPartitions];

    int maxSize = (int)Math.Ceiling(list.Count / (double)totalPartitions);
    int k = 0;

    for (int i = 0; i < partitions.Length; i++)
    {
        partitions[i] = new List<T>();
        for (int j = k; j < k + maxSize; j++)
        {
            if (j >= list.Count)
                break;
            partitions[i].Add(list[j]);
        }
        k += maxSize;
    }

    return partitions;
}

Initial URL
http://stackoverflow.com/questions/3892734/split-c-sharp-collection-into-equal-parts-maintaining-sort

Initial Description
author SomeMiscGuy@StackOverflow

Initial Title
Splitting C# list into equal parts

Initial Tags
list

Initial Language
C#