Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Splitting a Collection into Multiple Arrays - The Linq Way

0.00/5 (No votes)
1 Jun 2012 1  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here