拆分阵列到阵列2 C#
编辑:我曾尝试采取/跳过的方法,但我得到以下错误:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to
'string[]'. An explicit conversion exists (are you missing a cast?)
我不知道我在做什么错了,因为我复制了赛义德的code。
我有一个字符串数组(从20到300多件含有任何地方),我想将它拆分成2个独立的阵列,从第一个中间。
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.
我知道我可以用一个for循环做到这一点,但我想知道是否有这样做的更快/更好的办法。我还需要能够正确地分割的阵列,即使它有一个奇数的项目,例如:
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'
如果有人能帮助我或点我在正确的方向,这将是伟大的!
If anyone can help me or point me in the right direction, that will be great!
感谢
您可以使用LINQ:
firstArray = array.Take(array.Length / 2).ToArray();
secondArray = array.Skip(array.Length / 2).ToArray();
更新:为什么这个工程,独立于奇数或偶数
Update: Why this works, independent to odd or even numbers?
firstArray注意到 array.Length / 2
项目,第二个先跳过 array.Length / 2
项目,装置有第一和第二阵列之间没有冲突,即使在第一阵列的情况下 X
元件和第二阵列具有 X + 1
元素。奇数情况下,我们当然可以在阵列不能分成两部分,这样他们每个人都有一个相同数量的项目。
firstArray Takes array.Length / 2
items, and second one skips first array.Length / 2
items, means there is no conflict between first and second array, even in the case first array has x
element and second array has x+1
element. Of course in odd case we cannot split the array into two parts such that each of them have a same number of items.
此外,如果你想在上半场更多的项目(在奇数的情况下),这样做:
Also if you want to have more items 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();