Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

separate a string array to several small arrays

Tags:

c#

how can I separate an array in smaller arrays?

string[] str = new string[145]

I want two arrays for this; like

string[] str1 = new string[99];
string[] str2 = new string[46];

how can I do this from the source of str?

1- Then I want to put together the arrays into List all together but there is only add item? no add items? or any other way to make the string[145] array again..

like image 975
Bilgin Kılıç Avatar asked Dec 09 '22 15:12

Bilgin Kılıç


2 Answers

Simplest way, using LINQ:

string[] str1 = str.Take(99).ToArray();
string[] str2 = str.Skip(99).ToArray();

Putting them back together:

str = str1.Concat(str2).ToArray();

These won't be hugely efficient, but they're extremely simple :) If you need more efficiency, Array.Copy is probably the way to go... but it would take a little bit more effort to get right.

like image 104
Jon Skeet Avatar answered Dec 29 '22 03:12

Jon Skeet


You can use Array.Copy to get some of the items from the source array to another array.

string[] str1 = new string[99];
string[] str2 = new string[46];
Array.Copy(str, 0, str1, 0, 99);
Array.Copy(str, 99, str2, 0, 46);

You can use the same to copy them back.

like image 29
Oded Avatar answered Dec 29 '22 01:12

Oded