65.9K
CodeProject is changing. Read more.
Home

Splitting a Collection into Multiple Arrays - The Linq Way

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jun 2, 2012

CPOL
viewsIcon

18144

This is an alternative for "How to split an array into multiple arrays"

Introduction

This is an alternative to the original tip[^] but based on Linq. I want to use the method in a generic way, i.e. not re-invent the wheel for each new problem. And I want to make slices in a Linq style:

int n = 3;
int[] data = new int[] { 1,2,3,4,5,6,7,8,9,10,11,12,13,14};
foreach (var slice in data.GetSlices(n))
{
    Console.WriteLine(string.Join(",", slice));
}

Suggested Solution

public static class Ext
{
    public static IEnumerable<T[]> GetSlices<T>(this IEnumerable<T> source, int n)
    {
        IEnumerable<T> it = source;
        T[] slice = it.Take(n).ToArray();
        it = it.Skip(n);
        while (slice.Length != 0)
        {
            yield return slice;
            slice = it.Take(n).ToArray();
            it = it.Skip(n);
        }
    }
}

public class Program
{
    public static void Main()
    {
        int n = 3;
        int[] data = new int[] { 1,2,3,4,5,6,7,8,9,10,11,12,13,14};
        foreach (var slice in data.GetSlices(n))
        {
            Console.WriteLine(string.Join(",", slice));
        }
    }
}

Output:

1,2,3
4,5,6
7,8,9
10,11,12
13,14

History

  • V1.0, 2012-06-01: Initial version