Edit: I have tried the Take/Skip method but I get the following error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to
'string[]'. An explicit conversion exists (are you missing a cast?)
I do not know what I am doing wrong because I copied Saeed’s code.
I have a string array (containing anywhere from 20 to 300 items) and I want to split it into 2 separate arrays, from the middle of the first one.
I know how I can do this using a for loop but I would like to know if there was a faster/better way of doing it. I also need to be able to correctly split an array even if it has an odd number of items, eg:
string[] words = {"apple", "orange", "banana", "pear", "lemon"};
string[] firstarray, secondarray;
SplitArray(words, out firstarray, out secondarray); // Or some other function
// firstarray has the first 3 of the items from words, 'apple', 'orange' and 'banana'
// secondarray has the other 2, 'pear' and 'lemon'
You can use linq:
Why this works, despite the parity of the original array size?
The firstArray takes
array.Length / 2elements, and the second one skips the firstarray.Length / 2elements, it means there isn’t any conflict between these two arrays. Of course if the number of elements is odd we cannot split the array into two equal size parts.If you want to have more elements in the first half (in the odd case), do this: