65.9K
CodeProject is changing. Read more.
Home

How to Split an Array into Multiple Arrays

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

May 31, 2012

CPOL
viewsIcon

15378

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

Introduction

These days, I prefer to split arrays with autosize using the latest methodology, and always being as elegant as possible.

Using the Code

My ideas about changing code (different from the original) are:

  1. Avoid unnecessary if statements in for statements.
  2. Give the possibility to extract the splitted arrays to work with.
  3. Avoid null values.
static void Main(string[] args)
        {
            String[] arrayString = new string[] { "1", "2", "3", "4", "5","6","7" };

            List<string[]> splitted = new List<string[]>();

            Action<string[],> Split = (bulkarray, size) =>
                {
                    int i = -1;
                    int div = bulkarray.Length / size + (bulkarray.Length % size > 0 ? 1 : 0);

                    while (++i < div)
                        splitted.Add(bulkarray.Skip(size * i).Take(size).ToArray());
                };

            Split(arrayString, 3);
        }

I hope you find it interesting, because at least if you are learning C#, in this example you can learn several things.