Click here to Skip to main content
15,891,943 members
Articles / Programming Languages / C#
Tip/Trick

How to split an array into multiple arrays

Rate me:
Please Sign up or sign in to vote.
4.78/5 (6 votes)
6 May 2013CPOL 110.4K   9   6
How to split an array into different array of size n

Introduction

This tip will help you split an array of size m into multiple arrays of size n.

Using the code 

C++
String[] arrayString = new string[]{"","","","",""};
List<string[]> splitted = new List<string[]>();//This list will contain all the splitted arrays.
int lengthToSplit = 3;

int arrayLength = arrayString.Length;

for (int i = 0; i < arrayLength; i = i + lengthToSplit)
{
  string[] val = new string[lengthToSplit];
                
  if (arrayLength < i + lengthToSplit)
     {
        lengthToSplit = arrayLength - i;
     }
  Array.Copy(arrayString, i, val, 0, lengthToSplit);
  splitted.Add(val);
} 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionCorrecting last array Pin
Member 112126686-Nov-14 6:45
Member 112126686-Nov-14 6:45 
GeneralMy vote of 5 Pin
JayantaChatterjee13-May-13 4:27
professionalJayantaChatterjee13-May-13 4:27 
Questionsimpler solution with linq Pin
rrrado9-May-13 3:07
rrrado9-May-13 3:07 
or simpler

C#
int i = 0;
    arrayString.GroupBy(s => i++/lengthToSplit).Select(g => g.ToArray()).ToList()

AnswerRe: simpler solution with linq Pin
densat5-Jan-14 21:10
densat5-Jan-14 21:10 
QuestionThis may be quicker Pin
George Swan6-May-13 19:41
mveGeorge Swan6-May-13 19:41 
GeneralMy vote of 5 Pin
Member 418708230-May-12 1:51
Member 418708230-May-12 1:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.