Split Array by count - CSharp System

CSharp examples for System:Array Split

Description

Split Array by count

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*w  ww.ja  va2  s  . c o  m*/

public class Main{
        public static T[][] Spilte<T>(T[] source, int targetGroupCount)
        {
            if (source == null)
            {
                throw new Exception("source is NULL");
            }

            targetGroupCount = source.Length < targetGroupCount ? source.Length : targetGroupCount;
            int mode = source.Length % targetGroupCount;
            int div = source.Length / targetGroupCount;
            T[][] newArray = new T[targetGroupCount][];

            for (int i = 0; i < targetGroupCount; i++)
            {
                int len = div + (i < mode ? 1 : 0);
                int j = div * i + (i < mode ? i : mode);
                newArray[i] = new T[len];

                for (int k = 0; k < len; k++)
                {
                    newArray[i][k] = source[j + k];
                }
            }

            return newArray;
        }
}

Related Tutorials