Skip to main content

Partitioning a list in C#.NET means splitting a list of elements into smaller lists. How many lists are created or how big each partition is, depends on the context of each piece of source code.

//
// Number of Partitions
//
// The first way is to write a C# function that will take a list (or array) and
// the number of partitions we want, and split the list accordingly. Which means
// in this case, we don't care how big each list is, we just want a certain
// number of partitions.
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;
}

//
// Size of Partitions
//
// The second method is to instead give a C# function the original list and the
// maximum size of any each partition. The approach is very similar to the first
// method, but in this case we will never end up with empty partitions.
public static List<T>[] Partition2<T>(List<T> list, int size)
{
    if (list == null)
    {
        throw new ArgumentNullException("list");
    }

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

    int count = (int)Math.Ceiling(list.Count / (double)size);
    List<T>[] partitions = new List<T>[count];

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

    return partitions;
}