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'
The array_chunk() function splits an array into chunks of new arrays.
You can use linq:
firstArray = array.Take(array.Length / 2).ToArray();
secondArray = array.Skip(array.Length / 2).ToArray();
Why this works, despite the parity of the original array size?
The firstArray takes array.Length / 2
elements, and the second one skips the first array.Length / 2
elements, 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:
firstArray = array.Take((array.Length + 1) / 2).ToArray();
secondArray = array.Skip((array.Length + 1) / 2).ToArray();
string[] words = {"apple", "orange", "banana", "pear", "lemon"};
int mid = words.Length/2;
string[] first = words.Take(mid).ToArray();
string[] second = words.Skip(mid).ToArray();
If you don't want to/can't use LINQ you can simply do:
string[] words = { "apple", "orange", "banana", "pear", "lemon" };
string[] firstarray, secondarray;
int mid = words.Length / 2;
firstarray = new string[mid];
secondarray = new string[words.Length - mid];
Array.Copy(words, 0, firstarray, 0, mid);
Array.Copy(words, mid, secondarray, 0, secondarray.Length);
A more generalized approach that will split it into as many parts as you specify:
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
return list.Select((item, index) => new {index, item})
.GroupBy(x => (x.index + 1) / (list.Count()/parts) + 1)
.Select(x => x.Select(y => y.item));
}
*Edited Thanks skarmats
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With