Pages

Tuesday 22 September 2020

C# LINQ - Partitioning the List Collection Into Chunks

















Partitioning is the key part while working with the large collections in programming. LINQ helps in dividing the huge collection into chunks. 

Below code snippet takes the list and the chunk size and yields the chunks from the collection.

public static IEnumerable<List<T>> Partition<T>(List<T> source, Int32 size)
{
    for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
        yield return new List<T>(source.Skip(size * i).Take(size));
}

Test Results:





No comments:

Post a Comment