Click here to Skip to main content
12,447,096 members (51,946 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9.8K views
2 bookmarked
Posted

Splitting a Collection into Multiple Arrays - The Linq Way

, 1 Jun 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andreas Gieriet
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160811.3 | Last Updated 2 Jun 2012
Article Copyright 2012 by Andreas Gieriet
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid