Click here to Skip to main content
14,664,450 members
Articles » Languages » C# » Beginners
Tip/Trick
Posted 1 Jun 2012

Tagged as

Stats

16.3K views
2 bookmarked

Splitting a Collection into Multiple Arrays - The Linq Way

Rate this:
0.00 (No votes)
Please Sign up or sign in to vote.
0.00 (No votes)
1 Jun 2012CPOL
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).

Comments and Discussions

 
-- There are no messages in this forum --