4

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..

1
  • the most simple solution would be to use foreach ( ) or for ( ) or do you want to use LINQ ? Commented Jun 18, 2010 at 6:15

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice didn't thought of that :)
4

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.

1 Comment

It is the answer since we don't The LINQ over here.
0

To create a list, use the List<T>.AddRange method:

var array = new string[145];
var list = new List<string>();
list.AddRange(array);

2 Comments

note this answers only the 2nd question. Not the first one about seperating the array into 2 smaller arrays
@PoweRoy: That's because the first part had already been answered!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.